Static Generation of Dynamic Routes

Learn how to statically generate dynamically routed files in Next.js.

Overview

We’ve already seen how to statically generate a statically routed page, but now the question is: How can we statically generate dynamically routed pages?

To statically generate dynamic routes, we need a list of all possible paths for that dynamic route so that those pages can be prerendered during build time. For that, Next.js provides another out-of-the-box function named getStaticPaths().

Statically generating dynamic routes

Let’s talk a little about the getStaticPaths() function. Similar to getStaticProps(), it’s also an asynchronous function that comes with Next.js. The purpose of this method is to tell the Next.js compiler the list of possible paths a dynamic route can take during build time.

The getStaticPaths() function works together with the getStaticProps() function in dynamic routes to prerender the pages. Let's take a look at the syntax of the getStaticPaths() and getStaticProps() functions working together:

Press + to interact
export async function getStaticPaths(){
// return the data fetched from the external source
return {
paths: [
{
params: {
categoryName: 'Category1'
},
params: {
categoryName: 'Category2'
},
// ...
}
],
fallback: false,
}
}
export async function getStaticProps( {params} ){
// params comes from the getStaticPath function
const data = await fetch(URL)
return {
props: {
data
}
}
}

The getStaticPaths() function returns an array named paths, and a fallback. The paths array contains the list of possible paths the dynamic route can take. We’ll discuss the fallback option in the next lesson.

Let’s take a look at how this works. In the code below, we create a new file /pages/[category].js that uses the getStaticPaths function to pre-render all the possible paths:

import { Grid, Card, Typography } from '@mui/material';
import React from 'react'
import Image from 'next/image';
import styles from '../styles/Home.module.css'

const MealCard = (props) => {
    const {meals} = props

    return (
        <Grid container direction="row" alignItems="center" justifyContent="center" spacing={1} sx = {{flex: "wrap"}}>
        {
          meals.map((meal) => 
            <Grid item key={meal.idMeal}>
              <Card variant='outlined' className={styles.card}>
                <Grid container direction='column' justifyContent='center' alignItems='center' >
                  <Grid item 
                    className={styles.imgContainer}
                  >
                    <Image 
                      src = {meal.strMealThumb} 
                      alt={meal.strMeal} 
                      layout="fill"
                      objectFit="cover"
                      quality={100}
                    />
                  </Grid>
                  <Grid item>
                    <Typography variant='body1'>
                      {meal.strMeal}
                    </Typography>
                  </Grid>
                </Grid>
              </Card>
            </Grid>
          )
        }
      </Grid>
    )
}

export default MealCard;
Using getStaticPaths() in an application

The highlighted lines (lines 30–43) in the /page/categories/[category].js file show the getStaticPaths() function that we’ve implemented. We use the categories endpoint to get the list of categories that are the list of paths the dynamic route can take.

Note: The paths array must be in the form [{params: {pathname: path1}}, {params: {pathname: path2}}, {params: {pathname: path3}}]. Next.js doesn’t recognize the paths if they’re given in a different format.

The getStaticProps() function in line 45 takes {params} as an argument and is able to use the path names to generate the static props of this page.

So, what we can say is that the getStaticPaths() function tells the Next.js compiler the list of possible paths that the dynamic route can take so that all those routes can be pre-rendered. The getStaticProps() function takes the route of the path and uses it to fetch the content of the page for our API.