Next.js - Dynamic Routing



Dynamic Routing is powerful feature used in web applications. In this chapter we will learn what is dynamic routing, how to implement dynamic routing in Next.js, and how to catch all routes using dynamic routing.

What is Dynamic Routing?

Dynamic routes is a mechanism used in web application create flexible and reusable routes (URLs) based on dynamic parameters. This feature is essential when building applications where the routeing page depends on user input, database records, or other dynamic data. For example, if you want to generate a dynamic page based on the what user selected, you can use dynamic routing.

Dynamic Routing in Next.js

In Next.js, you can implement dynamic routing using variable folder name. For example consider following file structure in a Next.js app.

app/
 posts/
     [id]/
          page.jsx

In this example, [id] becomes a dynamic route that can match paths like:

  • /posts/1
  • /posts/abc

Example of Dynamic Product Page in Next.js

To create a dynamic route for a product page, start by creating a folder named "products" inside the `/app/` directory. Then, inside the "products" folder, create another folder named `[id]` and add `page.tsx` file inside it. The square brackets `[id]` indicate that this folder represents a dynamic route and the name can be changed based on the product selected by the user.

// app/products/[id]/page.tsx

"use client"
import { useParams } from 'next/navigation';

export default function ProductPage() {
  const { id } = useParams();

  return (
    <div>
      <h1>Product {id}</h1>
      <p>This is the product page for item {id}.</p>
    </div>
  );
}

Output

See the output below, page changes based on URL given.

Next Js Dynamic Routing

Catch-All Routes in Next.js

Catch-All routes are a type of dynamic routes that matches with all the slugs in current route. For example, /app/products/[...slug]/index.js will match with,

  • /products/smartphones
  • /products/electronics/laptop
  • /products/beauty-products/ladies/lipstick

Implement Catch-All Routes

To implement catch-all routing, define a directory square bracket directory with name starting with three dots. For example, [...productsSlug]. See the example below.

// app/products/[...slug]/page.tsx

export default function ProductPage({ params }: { params: { slug: string[] } }) {
  /* This route will match /products, 
     /products/electronics, /products/electronics/laptops */
  return (
    <div>
      <h1>Product Page</h1>
      <p>Matched Segments: {params.slug?.join(' / ') || 'No segments'}</p>
    </div>
  );
}

Output

In the output, all route in given format are accepted.

next.js-catch-all-route
Advertisements