What is generateStaticParams in Next.js: Explanation and Example
generateStaticParams is a Next.js function used in the App Router to specify dynamic route parameters at build time for static generation. It tells Next.js which pages to pre-render by returning an array of parameter objects. This helps create static pages for dynamic routes efficiently.How It Works
Imagine you have a website with pages that change based on some ID, like a blog with many posts. Instead of waiting for users to visit each page and then building it, generateStaticParams lets Next.js know all the possible IDs ahead of time. This way, Next.js can build all those pages when you build your site.
Think of it like preparing a photo album before a party. You gather all the photos (parameters) you want to show, so when guests arrive, everything is ready and loads instantly. generateStaticParams returns a list of these parameters, and Next.js uses them to create static pages for each one.
Example
This example shows how to use generateStaticParams to statically generate pages for blog posts with dynamic IDs.
export async function generateStaticParams() { // Simulate fetching post IDs from a data source const posts = [{ id: '1' }, { id: '2' }, { id: '3' }]; return posts.map(post => ({ id: post.id })); } export default function PostPage({ params }) { return <h1>Post ID: {params.id}</h1>; }
When to Use
Use generateStaticParams when you have dynamic routes and want to pre-build pages at build time for better performance and SEO. It is ideal for content that doesn't change often, like blogs, product pages, or documentation.
For example, if you have a product catalog, you can use generateStaticParams to list all product IDs so Next.js builds a static page for each product. This makes your site faster and reduces server load.
Key Points
- generateStaticParams runs at build time to list dynamic route parameters.
- It enables static generation of dynamic pages for faster load and SEO benefits.
- Returns an array of objects, each with keys matching dynamic route segments.
- Works only with Next.js App Router dynamic routes.
- Best for data that changes infrequently and can be pre-built.
Key Takeaways
generateStaticParams defines which dynamic pages Next.js builds statically at build time.