codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

5 / 73 topics
4File System Routing5Pages Directory6Dynamic Routes7Catch All Routes
Tutorials/Next.js/Pages Directory
▲Next.js

Pages Directory

Updated 2026-04-20
3 min read

Introduction

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.

Understanding the Pages Directory

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.

Basic Structure

Here's a basic structure of a Pages Directory:

my-next-app/
├── pages/
│   ├── index.js
│   ├── about.js
│   └── contact.js
└── ...
  • index.js: Represents the root route (/).
  • about.js: Represents the /about route.
  • contact.js: Represents the /contact route.

Creating a Simple Page

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 (/).

Dynamic Routes

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.

Creating a Dynamic Route

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.

Accessing Query Parameters

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.

Nested Routes

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.

Creating Nested Routes

To create nested routes, simply nest directories within the pages directory:

my-next-app/
├── pages/
│   ├── index.js
│   └── dashboard/
│       ├── index.js
│       └── settings.js
└── ...
  • dashboard/index.js: Represents the /dashboard route.
  • dashboard/settings.js: Represents the /dashboard/settings route.

Accessing Nested Routes

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>;
}

API Routes

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.

Creating an API Route

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.

Accessing the API Route

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>;
}

Best Practices

  • Consistent Naming: Use consistent and descriptive names for your pages to maintain a clean and organized directory structure.
  • Avoid Deep Nesting: While nested routes are powerful, avoid deep nesting as it can make the application harder to manage. Aim for a flat structure where possible.
  • Use Dynamic Routes Sparingly: Dynamic routes add complexity to your application. Use them only when necessary and ensure that they do not lead to performance issues.
  • Document API Routes: Clearly document your API routes, including expected request methods, parameters, and response formats.

Conclusion

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.


PreviousFile System RoutingNext Dynamic Routes

Recommended Gear

File System RoutingDynamic Routes