generateStaticParams

Pre-rendering dynamic routes at build time.

Next.js4 min readConcept 56 of 66

Build-Time Generation

generateStaticParams is an async function you can export from a dynamic route segment (like app/blog/[slug]/page.tsx).

Instead of waiting for a user to visit the page to render it, Next.js calls this function *during the build process*. It returns an array of parameters, and Next.js uses those parameters to instantly stamp out static HTML files for every route.

The Speed of Static

Static pages are significantly faster and cheaper to host than dynamic pages.

If you have an e-commerce store with 10,000 products, you don't want the server to do heavy database queries and React rendering every time a user clicks a product.

By using generateStaticParams, you pre-bake those 10,000 pages into static HTML and push them to a global CDN. When a user requests one, the CDN responds in milliseconds without ever waking up your origin server.

Implementation

tsx

// app/blog/[slug]/page.tsx

export async function generateStaticParams() {

const posts = await fetchPosts();

// The key 'slug' must match the folder name [slug]

return posts.map((post) => ({

slug: post.slug,

}));

}

The Build Matrix

Watch the Next.js compiler execute generateStaticParams at build time, converting a database array into physical HTML files.

Mode:

Next.js Compiler

// app/blog/[slug]/page.tsx
export async function generateStaticParams() {
return [
{ slug: 'apple' },
{ slug: 'banana' }
];
}
/blog/[slug]
apple.html
banana.html
Key Mismatch!Expected 'slug', got 'id'.
Falling back to dynamic rendering.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If your route folder is named `app/store/[category]/[item]/page.tsx`, what must `generateStaticParams` return?

Remember this

  • generateStaticParams only runs at build time, never at request time.
  • It converts dynamic SSR routes into blazing fast Static (SSG) routes.
  • The keys in the returned objects MUST perfectly match the bracketed folder names.
  • You can combine it with export const dynamicParams = false to return a 404 for any path not generated at build time.

Done with this concept?

Mark it complete to track your progress. No login needed.