Skip to content

Next.js Pages and Routing

One of the core features of Next.js is its file system-based routing system. This means you don't need to write complex routing configurations; simply create files and folders in the pages directory, and Next.js will automatically generate the corresponding routes.

Creating Pages

In Next.js, a page is a .js, .jsx, .ts, or .tsx file that exports a React component.

  • Creating the Homepage

    The pages/index.js file corresponds to the application's root path /.

    jsx
    // pages/index.js
    function HomePage() {
      return <h1>Welcome to the Homepage</h1>;
    }
    
    export default HomePage;
  • Creating Other Pages

    Create new files in the pages directory to generate new pages.

    • pages/about.js -> /about
    • pages/contact.js -> /contact
    jsx
    // pages/about.js
    function AboutPage() {
      return <h1>About Us</h1>;
    }
    
    export default AboutPage;
  • Nested Routes

    You can also create nested routes by creating folders.

    • pages/blog/index.js -> /blog
    • pages/blog/first-post.js -> /blog/first-post

In Next.js applications, you should use the next/link component for client-side route navigation. The Link component can prefetch pages for fast, seamless page transitions.

jsx
import Link from 'next/link';

function HomePage() {
  return (
    <div>
      <h1>Homepage</h1>
      <nav>
        <Link href="/about">
          <a>About Us</a>
        </Link>
        <Link href="/blog">
          <a>Blog</a>
        </Link>
      </nav>
    </div>
  );
}

export default HomePage;
  • href: The path to the target page.
  • The Link component's child element can be an <a> tag or any other interactive element.

Dynamic Routes

Next.js supports dynamic routes, allowing you to generate pages based on parameters. To create dynamic routes, use square brackets [] in the file name or directory name.

  • Single Dynamic Parameter

    For example, creating a pages/posts/[id].js file can match routes like /posts/1, /posts/abc, etc.

    jsx
    // pages/posts/[id].js
    import { useRouter } from 'next/router';
    
    function PostPage() {
      const router = useRouter();
      const { id } = router.query;
    
      return <h1>Post ID: {id}</h1>;
    }
    
    export default PostPage;

    You can use the useRouter hook to get route parameters.

  • Multiple Dynamic Parameters

    You can also create catch-all routes using [...slug] in the file name.

    For example, pages/docs/[...slug].js can match /docs/a, /docs/a/b, /docs/a/b/c, etc.

    jsx
    // pages/docs/[...slug].js
    import { useRouter } from 'next/router';
    
    function DocsPage() {
      const router = useRouter();
      const { slug = [] } = router.query;
    
      return <h1>Documentation Path: {slug.join('/')}</h1>;
    }
    
    export default DocsPage;

API Routes

Next.js allows you to create API endpoints in the pages/api directory. This makes building full-stack applications very simple.

  • Creating API Routes

    pages/api/user.js creates an API route at /api/user.

    javascript
    // pages/api/user.js
    export default function handler(req, res) {
      res.status(200).json({ name: 'John Doe' });
    }
    • req: An instance of http.IncomingMessage containing request information.
    • res: An instance of http.ServerResponse used to send responses.
  • Dynamic API Routes

    API routes also support dynamic parameters, such as pages/api/users/[id].js.

    javascript
    // pages/api/users/[id].js
    export default function handler(req, res) {
      const { id } = req.query;
      res.status(200).json({ userId: id });
    }

Summary

Next.js's routing system is intuitive and powerful. Through the file system, you can easily create static pages, dynamic pages, and API routes. Using the next/link component enables high-performance client-side navigation. Mastering these routing concepts is key to developing Next.js applications.

Previous Chapter: Next.js Project Explanation | Next Chapter: Next.js Data Fetching

Content is for learning and research only.