generateStaticParams
ThegenerateStaticParams function can be used in combination withdynamic route segments tostatically generate routes at build time instead of on-demand at request time.
generateStaticParams can be used with:
- Pages (
page.tsx/page.js) - Layouts (
layout.tsx/layout.js) - Route Handlers (
route.ts/route.js)
// Return a list of `params` to populate the [slug] dynamic segmentexportasyncfunctiongenerateStaticParams() {constposts=awaitfetch('https://.../posts').then((res)=>res.json())returnposts.map((post)=> ({ slug:post.slug, }))}// Multiple versions of this page will be statically generated// using the `params` returned by `generateStaticParams`exportdefaultasyncfunctionPage({ params,}: { params:Promise<{ slug:string }>}) {const {slug }=await params// ...}Good to know:
- You can use the
dynamicParamssegment config option to control what happens when a dynamic segment is visited that was not generated withgenerateStaticParams.- You must returnan empty array from
generateStaticParamsor utilizeexport const dynamic = 'force-static'in order to revalidate (ISR)paths at runtime.- During
next dev,generateStaticParamswill be called when you navigate to a route.- During
next build,generateStaticParamsruns before the corresponding Layouts or Pages are generated.- During revalidation (ISR),
generateStaticParamswill not be called again.generateStaticParamsreplaces thegetStaticPathsfunction in the Pages Router.
Parameters
options.params (optional)
If multiple dynamic segments in a route usegenerateStaticParams, the childgenerateStaticParams function is executed once for each set ofparams the parent generates.
Theparams object contains the populatedparams from the parentgenerateStaticParams, which can be used togenerate theparams in a child segment.
Returns
generateStaticParams should return an array of objects where each object represents the populated dynamic segments of a single route.
- Each property in the object is a dynamic segment to be filled in for the route.
- The properties name is the segment's name, and the properties value is what that segment should be filled in with.
| Example Route | generateStaticParams Return Type |
|---|---|
/product/[id] | { id: string }[] |
/products/[category]/[product] | { category: string, product: string }[] |
/products/[...slug] | { slug: string[] }[] |
Single Dynamic Segment
exportfunctiongenerateStaticParams() {return [{ id:'1' }, { id:'2' }, { id:'3' }]}// Three versions of this page will be statically generated// using the `params` returned by `generateStaticParams`// - /product/1// - /product/2// - /product/3exportdefaultasyncfunctionPage({ params,}: { params:Promise<{ id:string }>}) {const {id }=await params// ...}Multiple Dynamic Segments
exportfunctiongenerateStaticParams() {return [ { category:'a', product:'1' }, { category:'b', product:'2' }, { category:'c', product:'3' }, ]}// Three versions of this page will be statically generated// using the `params` returned by `generateStaticParams`// - /products/a/1// - /products/b/2// - /products/c/3exportdefaultasyncfunctionPage({ params,}: { params:Promise<{ category:string; product:string }>}) {const {category,product }=await params// ...}Catch-all Dynamic Segment
exportfunctiongenerateStaticParams() {return [{ slug: ['a','1'] }, { slug: ['b','2'] }, { slug: ['c','3'] }]}// Three versions of this page will be statically generated// using the `params` returned by `generateStaticParams`// - /product/a/1// - /product/b/2// - /product/c/3exportdefaultasyncfunctionPage({ params,}: { params:Promise<{ slug:string[] }>}) {const {slug }=await params// ...}Examples
Static Rendering
All paths at build time
To statically render all paths at build time, supply the full list of paths togenerateStaticParams:
exportasyncfunctiongenerateStaticParams() {constposts=awaitfetch('https://.../posts').then((res)=>res.json())returnposts.map((post)=> ({ slug:post.slug, }))}Subset of paths at build time
To statically render a subset of paths at build time, and the rest the first time they're visited at runtime, return a partial list of paths:
exportasyncfunctiongenerateStaticParams() {constposts=awaitfetch('https://.../posts').then((res)=>res.json())// Render the first 10 posts at build timereturnposts.slice(0,10).map((post)=> ({ slug:post.slug, }))}Then, by using thedynamicParams segment config option, you can control what happens when a dynamic segment is visited that was not generated withgenerateStaticParams.
// All posts besides the top 10 will be a 404exportconstdynamicParams=falseexportasyncfunctiongenerateStaticParams() {constposts=awaitfetch('https://.../posts').then((res)=>res.json())consttopPosts=posts.slice(0,10)returntopPosts.map((post)=> ({ slug:post.slug, }))}All paths at runtime
To statically render all paths the first time they're visited, return an empty array (no paths will be rendered at build time) or utilizeexport const dynamic = 'force-static':
exportasyncfunctiongenerateStaticParams() {return []}Good to know:
- You must always return an array from
generateStaticParams, even if it's empty. Otherwise, the route will be dynamically rendered.
exportconstdynamic='force-static'With Cache Components
When usingCache Components with dynamic routes,generateStaticParams must returnat least one param. Empty arrays cause abuild error. This allows Cache Components to validate your route doesn't incorrectly accesscookies(),headers(), orsearchParams at runtime.
Good to know: If you don't know the actual param values at build time, you can return a placeholder param (e.g.,
[{ slug: '__placeholder__' }]) for validation, then handle it in your page withnotFound(). However, this prevents build time validation from working effectively and may cause runtime errors.
See thedynamic routes section for detailed walkthroughs.
With Route Handlers
You can usegenerateStaticParams withRoute Handlers to statically generate API responses at build time:
exportasyncfunctiongenerateStaticParams() {return [{ id:'1' }, { id:'2' }, { id:'3' }]}exportasyncfunctionGET( request:Request, { params }:RouteContext<'/api/posts/[id]'>) {const {id }=await params// This will be statically generated for IDs 1, 2, and 3returnResponse.json({ id, title:`Post${id}` })}Route Handlers with Cache Components
When usingCache Components, combine withuse cache for optimal caching:
exportasyncfunctiongenerateStaticParams() {return [{ id:'1' }, { id:'2' }, { id:'3' }]}asyncfunctiongetPost(id:Promise<string>) {'use cache'constresolvedId=await idconstresponse=awaitfetch(`https://api.example.com/posts/${resolvedId}`)returnresponse.json()}exportasyncfunctionGET( request:Request, { params }:RouteContext<'/api/posts/[id]'>) {constpost=awaitgetPost(params.then((p)=>p.id))returnResponse.json(post)}See theRoute Handlers documentation for more details.
Disable rendering for unspecified paths
To prevent unspecified paths from being statically rendered at runtime, add theexport const dynamicParams = false option in a route segment. When this config option is used, only paths provided bygenerateStaticParams will be served, and unspecified routes will 404 or match (in the case ofcatch-all routes).
Multiple Dynamic Segments in a Route
You can generate params for dynamic segments above the current layout or page, butnot below. For example, given theapp/products/[category]/[product] route:
app/products/[category]/[product]/page.jscan generate params forboth[category]and[product].app/products/[category]/layout.jscanonly generate params for[category].
There are two approaches to generating params for a route with multiple dynamic segments:
Generate params from the bottom up
Generate multiple dynamic segments from the child route segment.
// Generate segments for both [category] and [product]exportasyncfunctiongenerateStaticParams() {constproducts=awaitfetch('https://.../products').then((res)=>res.json())returnproducts.map((product)=> ({ category:product.category.slug, product:product.id, }))}exportdefaultfunctionPage({ params,}: { params:Promise<{ category:string; product:string }>}) {// ...}Generate params from the top down
Generate the parent segments first and use the result to generate the child segments.
// Generate segments for [category]exportasyncfunctiongenerateStaticParams() {constproducts=awaitfetch('https://.../products').then((res)=>res.json())returnproducts.map((product)=> ({ category:product.category.slug, }))}exportdefaultfunctionLayout({ params,}: { params:Promise<{ category:string }>}) {// ...}A child route segment'sgenerateStaticParams function is executed once for each segment a parentgenerateStaticParams generates.
The childgenerateStaticParams function can use theparams returned from the parentgenerateStaticParams function to dynamically generate its own segments.
// Generate segments for [product] using the `params` passed from// the parent segment's `generateStaticParams` functionexportasyncfunctiongenerateStaticParams({ params: { category },}: { params: { category:string }}) {constproducts=awaitfetch(`https://.../products?category=${category}` ).then((res)=>res.json())returnproducts.map((product)=> ({ product:product.id, }))}exportdefaultfunctionPage({ params,}: { params:Promise<{ category:string; product:string }>}) {// ...}Notice that the params argument can be accessed synchronously and includes only parent segment params.
For type completion, you can make use of the TypeScriptAwaited helper in combination with eitherPage Props helper orLayout Props helper:
exportasyncfunctiongenerateStaticParams({ params: { category },}: { params:Awaited<LayoutProps<'/products/[category]'>['params']>}) {constproducts=awaitfetch(`https://.../products?category=${category}` ).then((res)=>res.json())returnproducts.map((product)=> ({ product:product.id, }))}Good to know:
fetchrequests are automaticallymemoized for the same data across allgenerate-prefixed functions, Layouts, Pages, and Server Components. Reactcachecan be used iffetchis unavailable.
Version History
| Version | Changes |
|---|---|
v13.0.0 | generateStaticParams introduced. |
Was this helpful?