How to Use generateStaticParams in Next.js for Static Pages
In Next.js,
generateStaticParams is an async function used in dynamic route segments to predefine all possible route parameters at build time for static generation. It returns an array of objects where each object contains params matching the dynamic segment names. This enables Next.js to generate static pages for each route ahead of time.Syntax
The generateStaticParams function must be exported from a dynamic route segment file. It returns an array of objects, each with keys matching the dynamic route parameters.
Example parts:
async function generateStaticParams(): declares the function as async.- Returns
Array<{ paramName: string }>: each object defines one route. - Used in files like
app/posts/[id]/page.tsxfor dynamic routes.
typescript
export async function generateStaticParams() { return [ { id: '1' }, { id: '2' }, { id: '3' } ]; }
Example
This example shows a Next.js dynamic route app/posts/[id]/page.tsx that uses generateStaticParams to statically generate pages for posts with IDs 1, 2, and 3.
The page component receives the params prop and renders the post ID.
typescript
export async function generateStaticParams() { return [ { id: '1' }, { id: '2' }, { id: '3' } ]; } export default function PostPage({ params }: { params: { id: string } }) { return <h1>Post ID: {params.id}</h1>; }
Output
<h1>Post ID: 1</h1> (for /posts/1), <h1>Post ID: 2</h1> (for /posts/2), <h1>Post ID: 3</h1> (for /posts/3)
Common Pitfalls
- Not returning an array of objects with keys matching the dynamic segment names causes build errors.
- Returning params with wrong key names will not generate routes correctly.
- Forgetting to export
generateStaticParamsmeans Next.js won't pre-generate pages. - Using
generateStaticParamsin non-dynamic routes has no effect.
typescript
/* Wrong: keys do not match dynamic segment name 'id' */ export async function generateStaticParams() { return [ { postId: '1' }, // should be { id: '1' } ]; } /* Correct: keys match dynamic segment */ export async function generateStaticParams() { return [ { id: '1' }, ]; }
Quick Reference
Tips for using generateStaticParams:
- Always export
generateStaticParamsfrom dynamic route files. - Return an array of objects with keys matching your dynamic route parameters.
- Use async functions to fetch data if needed.
- Helps Next.js build static pages for all routes at build time.
Key Takeaways
generateStaticParams defines all dynamic routes for static generation in Next.js.
Return an array of objects with keys matching your dynamic route parameters.
Always export generateStaticParams from your dynamic route segment file.
Use async logic inside generateStaticParams to fetch route data if needed.
Incorrect keys or missing export will cause static generation to fail.