React
Next.js
3 minute read | February 22, 2024

Statically rendering (SSG) dynamic routes with the Next.js App Router

By default your Next.js dynamic routes will be generated on demand at request time. But we can improve performance and SEO by statically generating them at build time instead. We'll use the built in generateStaticParams() function to achieve this. This tutorial assumes you are using the new Next.js App Router rather then the Pages Router.

Example

For this example we'll assume we have the following folder structure.

  • blog
    • page.jsx
    • [slug]
      • page.jsx

Lets update our "blog/[slug]/page.jsx" page by adding a generateStaticParams() function.

In order to use generateStaticParams your page must be a React Server Component

Javascript
export const generateStaticParams = async () => { }; const Page = ({ params }) => { const { slug } = params; return ( ...some ui ); }; export default Page;

This function needs to return an array of dynamic route segments that should be statically generated. In this example we'll assume we are fetching some data from an api but since this function only runs on the server you can also use the node file access api to load files from your web server.

Javascript
export const generateStaticParams = async () => { const response = await fetch('some url'); const posts = await response.json(); return posts.map((post) => ({ slug: post.slug, })) };

This will generate an many routes as there are posts. If we had three posts then the following routes would be generated.

  • /blog/{posts[0].slug}
  • /blog/{posts[1].slug}
  • /blog/{posts[2].slug}

Typescript

If you are using Typescript you can type the page props with the following interface.

Typescript
interface Props { params: { slug: string; } }