# Part 33: Static Generation for Dynamic Routes in Next.js

<figure><img src="https://159896965-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3LclXKUpANLoSt8DPdYV%2Fuploads%2FJK8G3Yjm1qHwjGSqwUcV%2F1675674296261.jpeg?alt=media&#x26;token=989182c4-9098-4bba-8dd9-52aeb4b0f941" alt=""><figcaption><p>Static Generation for Dynamic Routes in Next.js</p></figcaption></figure>

In our previous post, we discussed how to dynamically render reviews on the ReviewsPage component. Now, let's dive into how we can statically generate pages for dynamic routes in a Next.js application. This ensures that our pages are pre-rendered at build time, leading to faster load times and better performance.

### Understanding Dynamic Routes <a href="#viewer-fq7ts38309" id="viewer-fq7ts38309"></a>

Dynamic routes in Next.js allow us to create pages that match patterns and handle variable segments in the URL. For example, a path like /reviews/\[slug] can match multiple URLs such as /reviews/hellblade or /reviews/hollow-knight.

### The Need for Static Generation <a href="#viewer-jq82a38313" id="viewer-jq82a38313"></a>

While dynamic routes are powerful, they typically rely on server-side rendering (SSR) at runtime. This means that every time a user requests a page, the server must generate the HTML on-the-fly. While this is flexible, it can be slower compared to serving pre-generated static pages.

#### Benefits of Static Generation: <a href="#viewer-fantr38317" id="viewer-fantr38317"></a>

1. **Performance**: Pre-generated HTML files are served instantly without the need for server-side processing.
2. **Scalability**: Static files can be served by a CDN, reducing the load on your server.
3. **Reliability**: With fewer moving parts at runtime, static sites tend to be more reliable.

### Implementing Static Generation for Dynamic Routes <a href="#viewer-7fgzj38332" id="viewer-7fgzj38332"></a>

To statically generate pages even for dynamic routes, we need to inform Next.js about all the possible paths during the build process. This can be achieved using the generateStaticParams function.

#### Step-by-Step Implementation: <a href="#viewer-93rvc38336" id="viewer-93rvc38336"></a>

1. **Create a Function to Get Slugs**

   First, we need a function to get all the slugs (i.e., the unique identifiers for each review). This will help us determine which pages to statically generate.

```
//lib/reviews.js
import { readdir, readFile } from 'node:fs/promises';

export async function getReviews() {
  const slugs = await getSlugs();
  const reviews = [];  
  for (const slug of slugs) {
    const review = await getReview(slug);
    reviews.push(review);
  }
  return reviews;
}

export async function getSlugs() {
  const files = await readdir('./content/reviews');
  return files.filter((file) => file.endsWith('.md'))
    .map((file) => file.slice(0, -'.md'.length));
}
```

**2. Define generateStaticParams Function**

Next, we define the generateStaticParams function to return an array of paths that need to be pre-rendered. Each path is represented by an object containing the slug parameter.

```
//[slug]/page.jsx

import { getReview, getSlugs } from '@/lib/reviews';
export async function generateStaticParams() {
  const slugs = await getSlugs();
  return slugs.map((slug) => ({ slug }));
}
```

**3. Modify the ReviewPage Component**

We need to update the ReviewPage component to use the generateStaticParams function. This ensures that the component receives the correct slug parameter.

```
import Heading from '@/components/Heading';
import { getReview } from '@/lib/reviews';

export default async function ReviewPage({ params: { slug } }) {
  const review = await getReview(slug);
  console.log('[ReviewPage] rendering', slug);
  return (
    <>
      <Heading>{review.title}</Heading>
      <div dangerouslySetInnerHTML={{ __html: review.body }} />
    </>
  );
}
```

**4. Build and Test**

After implementing the above changes, we need to build our application to see the static generation in action.

```
npm run build
npm start
```

During the build process, Next.js will use the generateStaticParams function to determine which pages to pre-render. If successful, you'll see messages indicating that specific paths under /reviews/\[slug] have been statically generated.

### Conclusion <a href="#viewer-1v3lo38480" id="viewer-1v3lo38480"></a>

By implementing static generation for dynamic routes, we combine the flexibility of dynamic routing with the performance benefits of static sites. This approach ensures that users get fast and reliable access to our pages, while still allowing us to add new content dynamically.

With the steps outlined above, you can now pre-generate pages for any dynamic route in your Next.js application, making your site faster and more efficient. Happy coding!
