Loading...

Section

Basic Routing with the Pages Directory

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

One of the most fundamental aspects of any web application is its ability to navigate between different pages or views. In Next.js, this is elegantly handled through the pages directory. By default, Next.js uses a file-system-based router. This means that any file inside the pages directory automatically becomes a route in your application. Let's explore how this works.

At its core, the pages directory is where you'll define your application's routes. Each React component file within this directory corresponds to a specific URL path. This convention simplifies development significantly, as you don't need to manually configure routes in a separate file.

app/
└── pages/
    ├── _app.js
    ├── index.js
    └── about.js

In the structure above:

  • pages/index.js: This file will be accessible at the root of your application (e.g., /).
  • pages/about.js: This file will be accessible at the /about path.

Let's look at a simple example. Create a file named pages/index.js with the following content:

function HomePage() {
  return <h1>Welcome to my Next.js App!</h1>;
}

Now, create a file named pages/about.js with this content:

function AboutPage() {
  return <h1>About Us</h1>;
}

When you run your Next.js development server (npm run dev or yarn dev), you'll be able to navigate to http://localhost:3000/ to see the content from index.js, and http://localhost:3000/about to see the content from about.js. It's that straightforward!

graph LR;
    A[pages/index.js] --> B{http://localhost:3000/};
    C[pages/about.js] --> D{http://localhost:3000/about};

Nested routes are also automatically handled by the file structure. If you create a file at pages/products/[id].js, Next.js will create a dynamic route that matches /products/some-id where some-id can be any value.

app/
└── pages/
    ├── index.js
    ├── about.js
    └── products/
        └── [id].js

The [id].js file allows you to access the id parameter through the useRouter hook from next/router. This dynamic routing capability is crucial for building applications with varying content based on URL parameters.

In summary, the pages directory in Next.js provides a declarative and intuitive way to manage your application's routes, making it incredibly easy to get started and scale your project.