10 Routing with Next.js

Next.js features a straightforward and effective routing system based on the file structure in the pages directory. This structure simplifies the creation of new routes by just adding files, eliminating the need for separate routing configurations. This chapter discusses both the basics and advanced concepts of routing in Next.js.

10.1 Basic Routing

10.1.1 File-Based Routing

Each file in the pages directory automatically becomes a route. The file structure directly translates to the URL structure. For example:

10.1.2 Dynamic Routing

For dynamic routes, like custom URLs for blog posts, use square brackets ([]) in your file names. For example:

To navigate within your Next.js application, use the Link component from Next.js:

import Link from 'next/link';

// ...

<Link href="/about">
  <a>About Us</a>
</Link>

This component enables client-side routing with optimized prefetching.

10.2 Advanced Routing

10.2.1 API Routes

Next.js also allows the definition of API routes. By adding JavaScript files to the pages/api directory, you can create server-side API endpoints. For example:

10.2.2 Catch-all Routes

For more complex routing patterns, catch-all routes can be used. A file like pages/[...slug].js can capture multiple URL segments in an array.

10.2.3 Redirects and Rewrites

Redirects and rewrites can be configured in the next.config.js to tailor the routing behavior to your needs.

Routing in Next.js is intuitive and powerful, thanks to the file-based approach that does away with the need for separate routing configurations. With features like dynamic routing, API routes, catch-all routes, and the ability to define redirects and rewrites, Next.js offers developers the flexibility to efficiently design complex application structures.

10.2.4 Exercise: Introduction to Routing with Next.js

10.2.4.1 Task 1: Project Setup

10.2.4.2 Task 2: Static Routes

10.2.4.3 Task 3: Dynamic Routing

10.2.4.4 Task 4: Linking Pages

10.2.4.5 Task 5: Testing

10.2.4.6 Bonus: Advanced Routing

10.2.5 App Router: A new era of routing

With the introduction of the App Router in Next.js, developers now have the option of defining routes programmatically. This is done via a manifest file that allows explicit control over routing behavior. This option is particularly useful for complex applications that require advanced routing patterns and custom middleware. It is important to decide whether to use the App Router when creating a new application with create-next-app, as it provides a different routing structure than the traditional Pages Router.

Routing in Next.js is intuitive and powerful, thanks to the file-based approach that eliminates the need for separate routing configurations. With features such as dynamic routing, API routes, catch-all routes and the ability to define redirects and rewrites, Next.js gives developers the flexibility to efficiently design complex application structures.