Loading...

Section

Understanding Pages in Next.js

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

Follow The Prince Academy Inc.

In Next.js, the concept of a 'page' is fundamental to how your application is structured and how users navigate through it. Unlike traditional single-page applications where you might manually manage routes and UI components, Next.js offers a file-system-based routing convention that significantly simplifies page creation and management.

At its core, each file inside the pages directory of your Next.js project automatically becomes a route. This means that if you create a file named about.js within the pages directory, Next.js will automatically create a route for /about. Visiting this URL in the browser will render the React component exported from that about.js file.

import React from 'react';

function AboutPage() {
  return (
    <div>
      <h1>About Us</h1>
      <p>Learn more about our company.</p>
    </div>
  );
}

export default AboutPage;

The root of your application, the homepage, is represented by the index.js file within the pages directory. So, pages/index.js maps to the / route.

graph TD;
  A[pages/index.js] --> B[/];
  C[pages/about.js] --> D[/about];
  E[pages/contact.js] --> F[/contact];
  G[pages/products/[id].js] --> H[/products/:id];

Beyond simple static pages, Next.js also supports dynamic routing. You can create pages with dynamic segments by using square brackets in your filenames. For example, a file named pages/products/[id].js will create a route that matches URLs like /products/1, /products/abc, or any other value after /products/. The id part will be available as a parameter within your page component.

import React from 'react';
import { useRouter } from 'next/router';

function ProductDetail() {
  const router = useRouter();
  const { id } = router.query;

  return (
    <div>
      <h1>Product Details</h1>
      <p>Showing details for product ID: {id}</p>
    </div>
  );
}

export default ProductDetail;

This file-system-based routing is a powerful feature that makes setting up routes incredibly intuitive and reduces the need for explicit routing configuration. It aligns with the idea of treating your application's structure as code, making it easier to understand and maintain.