Dynamic Routing

Learn how to create dynamic routes in a Next.js application.

Why we need dynamic routing

Next.js also comes with an effective out-of-the-box way of handling dynamic routes. We’ll start off with the basics of creating dynamic routes with Next.js. But why would we need dynamic routing? In almost all real-world web applications, dynamic routing is a big part of how they work. For example, in social media applications, the profile page for all users has the same markup, but each user's content is different. This is where we can use dynamic routing to change the content of the page but have the same page layout for each user.

Creating dynamically routed files

Because routing is handled using file names by Next.js, the router needs to be told if the route is dynamic. To create a dynamically routed file in Next.js, we need to use [] to encapsulate the file name, for example, [id].js. This translates to /:id in our URL. Next.js then takes the :id portion of the URL and saves it in a variable named id that we can use from the router.

A few things to note with dynamic routes are:

  • /pages/[id].js would be mapped to /:id.

  • /pages/collections/[collection].js would be mapped to /collections/:collection.

  • /pages/[collection]/about-collection.js would be mapped to /:collection/about-collection.

Let's take a look at how to work with dynamic routes with the example in the code widget below:

import React from 'react'
import Link from 'next/link';
import styles from '../styles/Header.module.css'
import { useRouter } from 'next/router';

const Header = () => {
  const router = useRouter();

  const handleHomeRoute = (e) => {
    e.preventDefault()
    router.push('/')
  }

  return (
    <div className={styles.container}>
      <div 
        className={styles.link}
        onClick = {handleHomeRoute}
      >
        Home
      </div>
      <div className={styles.linkContainer}>
        <div className={styles.link}>
          <Link href='/about'>About</Link>
        </div>
        <div className={styles.link}>
          <Link href='/collections'>Collections</Link>
        </div>
      </div>
    </div>
  )
}

export default Header;
Dynamic routing in Next.js

For the code above, any route that matches collections/[collection].js is matched to the [collection].js file and displays that page. The parameter of the matched path is sent to the page as an object of the router, named query. In line 6, we use the router.query object to get the name of the path. For example, the object for the route collections/collection1 looks like the following:

{ collection: "collection1" }

Note: Try appending a string to /collections/ in the URL of our application. Whatever is in that part of the URL is stored in the collection variable of the page.

When to use dynamic routes

Generally, dynamic routes are used to serve the same template as HTML, which displays different data from an external source like this:

Press + to interact
import { useRouter } from 'next/router'
export default function Collection() {
const router = useRouter()
const {collection} = router.query;
// Use collection for API call
const data = await fetch (`URL/${collection}`)
return (
// Use the data from the API to display into HTML
<div>
{data}
</div>
)
}

So, whenever we have a page that has the same HTML template but displays different data, we should use dynamic routing.