In this section, we will explore the Pages Directory in Next.js, a core concept that allows you to define routes and pages for your application. The Pages Directory is one of the fundamental building blocks of a Next.js project, enabling developers to create server-side rendered (SSR) or statically generated pages with ease.
The Pages Directory is located at the root level of your Next.js project (pages/). Each file within this directory corresponds to a route in your application. For example, if you have a file named about.js inside the pages directory, it will be accessible via the /about URL.
Here's a basic structure of a Pages Directory:
my-next-app/
├── pages/
│ ├── index.js
│ ├── about.js
│ └── contact.js
└── ...
/)./about route./contact route.Let's create a simple page using Next.js. We'll start with an index.js file in the pages directory:
// pages/index.js
export default function HomePage() {
return <h1>Welcome to My Next.js App!</h1>;
}
This code defines a functional component that returns a heading. When you run your Next.js application, this page will be accessible at the root URL (/).
Next.js supports dynamic routes, allowing you to create pages with variable segments in their URLs. This is useful for creating blog posts, product pages, or any other content that requires unique URLs.
To create a dynamic route, you can use square brackets [] around the segment of the URL that should be dynamic. For example, let's create a page for individual blog posts:
// pages/posts/[id].js
export default function Post({ params }) {
const { id } = params;
return <h1>Post: {id}</h1>;
}
In this example, [id] is a dynamic segment that captures the value from the URL. The params object contains all the dynamic segments as key-value pairs.
You can also access query parameters using the useRouter hook from Next.js:
// pages/posts/[id].js
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id, slug } = router.query;
return (
<div>
<h1>Post: {id}</h1>
<p>Slug: {slug}</p>
</div>
);
}
In this example, we access the id and slug query parameters from the URL.
Next.js also supports nested routes, which allow you to create a hierarchy of pages. This is useful for organizing your application into sections or modules.
To create nested routes, simply nest directories within the pages directory:
my-next-app/
├── pages/
│ ├── index.js
│ └── dashboard/
│ ├── index.js
│ └── settings.js
└── ...
/dashboard route./dashboard/settings route.You can access nested routes just like any other page:
// pages/dashboard/index.js
export default function Dashboard() {
return <h1>Welcome to your Dashboard</h1>;
}
Next.js also allows you to create API routes within the Pages Directory. This is useful for handling server-side logic, such as fetching data from an external API or interacting with a database.
To create an API route, simply prefix the file name with api/:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js!' });
}
In this example, we define a simple API endpoint that returns a JSON response.
You can access the API route using an HTTP client or directly in your application:
// pages/index.js
import { useEffect, useState } from 'react';
export default function HomePage() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/hello')
.then((res) => res.json())
.then((data) => setMessage(data.message));
}, []);
return <h1>{message}</h1>;
}
The Pages Directory is a powerful feature in Next.js that simplifies the process of creating routes and pages for your application. By understanding how to use static and dynamic routes, nested routes, and API routes, you can build robust and scalable applications with ease. In the next section, we will explore other core concepts in Next.js, such as server-side rendering and static generation.