Pre-render Pages
Used in this guide:Static Generation vs. Server-Side Rendering
Next.js Server Components (default behavior for async components without generateStaticParams) perform data fetching on every request.
If your pages (eg. blog posts) are relatively static, you can significantly improve performance by generating these pages statically at build time (Static Site Generation or Incremental Static Regeneration) so that Next.js can serve the pre-rendered HTML without needing to connect to the database on every visit.
What is generateStaticParams?
It is a function specific to the Next.js App Router used for dynamic routes (eg. app/blog/[slug]/page.tsx).
Its purpose is to tell Next.js which paths for a dynamic segment should be statically generated at build time. When this function is exported from a dynamic route segment file, Next.js executes it during the build process to determine all possible values for that segment.
export async function generateStaticParams() {
// 1. Fetch all blog posts
const { posts } = await getBlogPosts();
// 2. Safety check
if (!posts || !Array.isArray(posts)) {
return [];
}
// 3. Format the data for Next.js
return posts.map((post: BlogPost) => ({
slug: post.slug,
}));
}We usually put this example function inside a slug page (eg. app/blog/[slug]/page.tsx) right after the import section.
Explanation
First, we fetch all blog posts using a helper function. Then we make sure that the result is an array, if not (if we didn't get an array of posts) we return an empty array instead.
Otherwise, we proceed to map() through the posts array. And each iteration returns an object of key value pair (key = slug, value = post.slug). In the end, we end up with an array of objects similar to this:
[
{ slug: 'post-title-1' },
{ slug: 'post-title-2' },
// ... and so on for all posts fetched
]Next.js then uses that array as a blueprint for Static Site Generation (SSG) during the build process.
Next.js Interprets the Parameters
Next.js reads the array returned by generateStaticParams(). Each object in the array defines the value for the dynamic segment in your route.
Since your route is app/blog/[slug]/page.tsx, Next.js knows that the slug property in each object corresponds to the [slug] segment.
Next.js then proceeds to render all the slug pages for each of these generated paths at build time.