Next.js is a popular framework for building React applications that support server-side rendering, static site generation, and incremental static regeneration. One of the features that Next.js provides is a file-system based router, where folders and files in the app directory are mapped to URL paths.
However, sometimes you may want to create routes that depend on dynamic data, such as the slug of a blog post, the id of a product, or the name of a user. For example, you may want to have a page that shows the details of a blog post with a URL like /blog/how-to-use-next-js
, where how-to-use-next-js
is the slug of the post.
This is where dynamic routes come in handy. Dynamic routes are a way to create pages that can match any URL segment, and fetch the data for that segment at build time or request time. By using dynamic routes, you can achieve the following benefits:
/blog/[slug]
, /products/[id]
, or /users/[name]
.In this article, we will show you how to use dynamic routes in Next.js, and how to fetch and pre-render the data for each page.
To create a dynamic route, you need to wrap a folder’s name in square brackets, such as [slug]
, [id]
, or [name]
. This tells Next.js that this folder is a dynamic route, and it can match any URL segment. For example, if you have the following folder structure:
app
├── blog
│ ├── [slug].js
│ └── index.js
├── products
│ ├── [id].js
│ └── index.js
├── users
│ ├── [name].js
│ └── index.js
└── index.js
The corresponding URL paths for the pages are:
/
/blog
/blog/how-to-use-next-js
/blog/another-post
/products
/products/123
/products/456
/users
/users/alice
/users/bob
As you can see, the dynamic route names are replaced by the URL segments, and they can match any value.
One of the main use cases for dynamic routes is to fetch and pre-render the data for each page based on the URL segment. For example, you may want to fetch the blog post data from an API or a file system based on the slug, and pre-render the page with the post content.
To do this, you need to use a function that Next.js provides: generateStaticParams
. This function allows you to specify the possible values for the URL segments, and fetch the data for each page at build time. You can also use fallback
and revalidate
options to enable incremental static regeneration, which allows you to update the pages after the initial build.
The generateStaticParams
function should return an array of objects that contain the params
property, which specifies the value for the URL segment. For example, the generateStaticParams
function for the blog route group could look something like this:
export async function generateStaticParams() {
// Fetch the slugs of all posts from an API or a file system
const slugs = await fetchSlugs();
// Map the slugs to the params objects
const params = slugs.map((slug) => ({
slug,
}));
return params;
}
Then, in the page component inside the blog route group, you can use the params
prop to fetch the data and render the post content. For example, the [slug].js
file for the blog route group could look something like this:
import React from 'react';
import Link from 'next/link';
export default function BlogPost({ params }) {
// Get the slug from the params prop
const { slug } = params;
// Fetch the post data from an API or a file system based on the slug
const post = await fetchPost(slug);
return (
<div className="blog-post"> <h1>{post.title}</h1> <p>{post.date}</p> <div dangerouslySetInnerHTML={{ __html: post.content }} /> <Link href="/blog"> <a>Back to blog</a> </Link> </div>
);
}
You can create similar generateStaticParams
functions for other dynamic routes, such as products and users, and customize them according to your needs.
Dynamic routes are a powerful feature of Next.js that allow you to create pages that can match any URL segment, and fetch and pre-render the data for each page. By using generateStaticParams
, you can simplify the creation of dynamic routes and improve the performance of your Next.js application.
If you want to learn more about dynamic routes and generateStaticParams
, you can check out the official documentation.