Getting Starting with Next.js
What is Next.js?
Next.js is an open-source JavaScript library built on top of React. It's designed to simplify the development process by providing out-of-the-box features like automatic code splitting, server-side rendering (SSR), static site generation (SSG), and more.
Why Use Next.js?
- Automatic Code Splitting: Next.js automatically splits your code into smaller chunks so that only the necessary code is loaded for each page.
- Server-Side Rendering (SSR): This allows search engines to index pages properly and provides a better user experience by rendering content on the server before sending it to the client.
- Static Site Generation (SSG): You can pre-render pages at build time, which is great for SEO and performance.
- Built-in CSS Support: Next.js includes support for styled JSX and Sass out of the box.
- API Routes: Next.js allows you to create API routes directly within your application.
- Image Optimization: Next.js provides a built-in image optimization library that helps reduce page load times.
Getting Started with Next.js
- Install Node.js: Ensure Node.js is installed on your machine. You can download it from the official Node.js website.
- Create a New Project: Use the
create-next-app
command to create a new Next.js project.
npx create-next-app@latest my-next-app
cd my-next-app
Basic Structure of a Next.js Project
A basic Next.js project has the following structure:
my-next-app/
├── node_modules/
├── public/
│ └── favicon.ico
├── styles/
│ └── globals.css
├── .gitignore
├── package.json
├── README.md
└── pages/
├── api/
│ └── hello.js
├── index.js
└── ...
Pages Directory
Next.js uses the pages
directory to define your application's routes. Each file in this directory corresponds to a route.
For example, pages/index.js
is the home page:
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js!</h1>;
}
You can create new pages by adding new files to the pages
directory. For example, creating a about.js
file will automatically create an /about
route.
Components and JSX
Next.js uses React components and JSX (JavaScript XML) for building UIs. You can import and use any React component in your Next.js application.
// pages/about.js
import { useState } from 'react';
export default function About() {
const [count, setCount] = useState(0);
return (
<div>
<h1>About Page</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Styling
Next.js supports a variety of styling options, including CSS Modules and styled components.
Using CSS Modules
Create a styles/Home.module.css
file:
/* styles/Home.module.css */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
Then, import and use it in your component:
// pages/index.js
import styles from '../styles/Home.module.css';
export default function Home() {
return (
<div className={styles.container}>
<h1>Welcome to Next.js!</h1>
</div>
);
}
Using Styled Components
First, install styled components:
npm install styled-components
Then, create a styles/GlobalStyles.js
file:
// styles/GlobalStyles.js
import { createGlobalStyle } from 'styled-components';
const GlobalStyles = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
`;
export default GlobalStyles;
Import and use it in your _app.js
file:
// pages/_app.js
import '../styles/GlobalStyles.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
API Routes
Next.js allows you to create API routes directly within your application. Create a new file in the pages/api
directory.
For example, create a hello.js
file:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' });
}
You can access this API route by visiting /api/hello
in your browser or using tools like curl
.
Static Site Generation (SSG)
Next.js supports static site generation out of the box. You can use the getStaticProps
function to pre-render pages at build time.
Create a posts.js
file:
// pages/posts.js
export default function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export async function getStaticProps() {
// Fetch posts from an API or database
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return {
props: {
posts,
},
};
}
Server-Side Rendering (SSR)
Next.js also supports server-side rendering. You can use the getServerSideProps
function to render pages on each request.
Create a blog.js
file:
// pages/blog.js
export default function Blog({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
export async function getServerSideProps(context) {
// Fetch the blog post based on context.params.id
const res = await fetch(`https://api.example.com/blog/${context.params.id}`);
const post = await res.json();
return {
props: {
post,
},
};
}
You can access this page by visiting /blog/[id]
, where [id]
is a dynamic parameter.
Conclusion
This should give you a solid foundation to get started with Next.js. You can explore more advanced features like image optimization, internationalization (i18n), and more in the official Next.js documentation.