-[`params`](/docs/app/api-reference/file-conventions/page#params-optional) - Dynamic route parameters (unless at least one sample is provided via [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params))
-[`params`](/docs/app/api-reference/file-conventions/page#params-optional) - Dynamic route parameters (unless at least one sample is provided via [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params)). See [Dynamic Routes with Cache Components](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components) for detailed patterns.
-Sincethe`params`propisapromise.Youmustuse`async`/`await`orReact's use function to access the values.
-Sincethe`params`propisapromise.Youmustuse`async`/`await`orReact's use function to access the values.
- In version 14 and earlier, `params` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- In version 14 and earlier, `params` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
### With Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components) with dynamic route segments, how you handle params depends on whether you use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params).
Without `generateStaticParams`, param values are unknown during prerendering, making params runtime data. You must wrap param access in `<Suspense>` boundaries to provide fallback UI.
With `generateStaticParams`, you provide sample param values that can be used at build time. The build process validates that dynamic content and other runtime APIs are correctly handled, then generates static HTML files for the samples. Pages rendered with runtime params are saved to disk after a successful first request.
The sections below demonstrate both patterns.
#### Without `generateStaticParams`
All params are runtime data. Param access must be wrapped by Suspense fallback UI. Next.js generates a static shell at build time, and content loads on each request.
> **Good to know**: You can also use [`loading.tsx`](/docs/app/api-reference/file-conventions/loading) for page-level fallback UI.
```tsx filename="app/blog/[slug]/page.tsx"
import { Suspense } from 'react'
export default function Page({ params }: PageProps<'/blog/[slug]'>) {
return (
<div>
<h1>Blog Post</h1>
<Suspense fallback={<div>Loading...</div>}>
{params.then(({ slug }) => (
<Content slug={slug} />
))}
</Suspense>
</div>
)
}
async function Content({ slug }: { slug: string }) {
const res = await fetch(`https://api.vercel.app/blog/${slug}`)
const post = await res.json()
return (
<article>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
)
}
```
#### With `generateStaticParams`
Provide params ahead of time to prerender pages at build time. You can prerender all routes or a subset depending on your needs.
During the build process, the route is executed with each sample param to collect the HTML result. If dynamic content or runtime data are accessed incorrectly, the build will fail.
export default async function Page({ params }: PageProps<'/blog/[slug]'>) {
const { slug } = await params
return (
<div>
<h1>Blog Post</h1>
<Content slug={slug} />
</div>
)
}
async function Content({ slug }: { slug: string }) {
const post = await getPost(slug)
return (
<article>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
)
}
async function getPost(slug: string) {
'usecache'
const res = await fetch(`https://api.vercel.app/blog/${slug}`)
return res.json()
}
```
Build-time validation only covers code paths that execute with the sample params. If your route has conditional logic that accesses runtime APIs for certain param values not in your samples, those branches won'tbevalidatedatbuildtime:
export default async function Page({ params }: PageProps<'/blog/[slug]'>) {
const { slug } = await params
if (slug.startsWith('private-')) {
// This branch is never executed at build time
// Runtime requests for 'private-*' slugs will error
return <PrivatePost slug={slug} />
}
return <PublicPost slug={slug} />
}
async function PrivatePost({ slug }: { slug: string }) {
const token = (await cookies()).get('token')
// ... fetch and render private post using token for auth
}
```
Forruntimeparamsnotreturnedby`generateStaticParams`,validationoccursduringthefirstrequest.Intheexampleabove,requestsforslugsstartingwith`private-`willfailbecause`PrivatePost`accesses`cookies()`withoutaSuspenseboundary.Otherruntimeparamsthatdon't hit the conditional branch will render successfully and be saved to disk for subsequent requests.
export default async function Page({ params }: PageProps<'/blog/[slug]'>) {
const { slug } = await params
if (slug.startsWith('private-')) {
return (
<Suspense fallback={<div>Loading...</div>}>
<PrivatePost slug={slug} />
</Suspense>
)
}
return <PublicPost slug={slug} />
}
async function PrivatePost({ slug }: { slug: string }) {
const token = (await cookies()).get('token')
// ... fetch and render private post using token for auth
}
```
## Examples
## Examples
### With `generateStaticParams`
### With `generateStaticParams`
...
@@ -172,3 +316,60 @@ export async function generateStaticParams() {
...
@@ -172,3 +316,60 @@ export async function generateStaticParams() {
```
```
When using `fetch` inside the `generateStaticParams` function, the requests are [automatically deduplicated](/docs/app/guides/caching#request-memoization). This avoids multiple network calls for the same data Layouts, Pages, and other `generateStaticParams` functions, speeding up build time.
When using `fetch` inside the `generateStaticParams` function, the requests are [automatically deduplicated](/docs/app/guides/caching#request-memoization). This avoids multiple network calls for the same data Layouts, Pages, and other `generateStaticParams` functions, speeding up build time.
### Dynamic GET Route Handlers with `generateStaticParams`
`generateStaticParams` also works with dynamic [Route Handlers](/docs/app/api-reference/file-conventions/route) to statically generate API responses at build time:
In this example, route handlers for all blog post IDs returned by `generateStaticParams`willbestaticallygeneratedatbuildtime.RequeststootherIDswillbehandleddynamicallyatrequesttime.
#### Static Generation with `generateStaticParams`
You can use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) with dynamic Route Handlers to statically generate responses at build time for specified params, while handling other params dynamically at request time.
When using [Cache Components](/docs/app/getting-started/cache-components), you can combine `generateStaticParams` with `use cache` to enable data caching for both prerendered and runtime params.
See the [generateStaticParams with Route Handlers](/docs/app/api-reference/functions/generate-static-params#with-route-handlers) documentation for examples and details.
### URL Query Parameters
### URL Query Parameters
The request object passed to the Route Handler is a `NextRequest` instance, which includes [some additional convenience methods](/docs/app/api-reference/functions/next-request#nexturl), such as those for more easily handling query parameters.
The request object passed to the Route Handler is a `NextRequest` instance, which includes [some additional convenience methods](/docs/app/api-reference/functions/next-request#nexturl), such as those for more easily handling query parameters.
@@ -5,6 +5,12 @@ description: API reference for the generateStaticParams function.
...
@@ -5,6 +5,12 @@ description: API reference for the generateStaticParams function.
The`generateStaticParams`functioncanbeusedincombinationwith[dynamicroutesegments](/docs/app/api-reference/file-conventions/dynamic-routes)to[**staticallygenerate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
The`generateStaticParams`functioncanbeusedincombinationwith[dynamicroutesegments](/docs/app/api-reference/file-conventions/dynamic-routes)to[**staticallygenerate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
// Return a list of `params` to populate the [slug] dynamic segment
// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
export async function generateStaticParams() {
...
@@ -291,12 +297,80 @@ export async function generateStaticParams() {
...
@@ -291,12 +297,80 @@ export async function generateStaticParams() {
}
}
```
```
> **Good to know:** You must always return an array from `generateStaticParams`, even if it'sempty.Otherwise,theroutewillbedynamicallyrendered.
> **Good to know:**
>
> - You must always return an array from `generateStaticParams`, even if it'sempty.Otherwise,theroutewillbedynamicallyrendered.
```jsx filename="app/changelog/[slug]/page.js"
```jsx filename="app/changelog/[slug]/page.js"
export const dynamic = 'force-static'
export const dynamic = 'force-static'
```
```
#### With Cache Components
Whenusing[CacheComponents](/docs/app/getting-started/cache-components)withdynamicroutes,`generateStaticParams`mustreturn**atleastoneparam**.Emptyarrayscausea[builderror](/docs/messages/empty-generate-static-params).ThisallowsCacheComponentstovalidateyourroutedoesn't incorrectly access `cookies()`, `headers()`, or `searchParams` at runtime.
> **Good to know**: If you don'tknowtheactualparamvaluesatbuildtime,youcanreturnaplaceholderparam(e.g.,`[{ slug: '__placeholder__' }]`)forvalidation,thenhandleitinyourpagewith`notFound()`.However,thispreventsbuildtimevalidationfromworkingeffectivelyandmaycauseruntimeerrors.
Seethe[dynamicroutessection](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components) for detailed walkthroughs.
@@ -4,7 +4,7 @@ title: Empty generateStaticParams with Cache Components
...
@@ -4,7 +4,7 @@ title: Empty generateStaticParams with Cache Components
## Why This Error Occurred
## Why This Error Occurred
You're using [Cache Components](https://nextjs.org/docs/beta/app/api-reference/config/next-config-js/cacheComponents) in your Next.js application, and one of your `generateStaticParams` functions returned an empty array, which causes a build error.
You're using [Cache Components](https://nextjs.org/docs/app/getting-started/cache-components) in your Next.js application, and one of your `generateStaticParams` functions returned an empty array, which causes a build error.
When Cache Components is enabled, Next.js performs build-time validation to ensure your routes can be properly prerendered without runtime dynamic access errors. If `generateStaticParams` returns an empty array, Next.js cannot validate that your route won'taccessdynamicvalues(like`await cookies()`,`await headers()`,or`await searchParams`)atruntime,whichwouldcauseerrors.
When Cache Components is enabled, Next.js performs build-time validation to ensure your routes can be properly prerendered without runtime dynamic access errors. If `generateStaticParams` returns an empty array, Next.js cannot validate that your route won'taccessdynamicvalues(like`await cookies()`,`await headers()`,or`await searchParams`)atruntime,whichwouldcauseerrors.
...
@@ -21,27 +21,31 @@ This strict requirement ensures:
...
@@ -21,27 +21,31 @@ This strict requirement ensures:
Modify your `generateStaticParams` function to return at least one set of parameters. This is the most common fix and allows build-time validation to work properly.
Modify your `generateStaticParams` function to return at least one set of parameters. This is the most common fix and allows build-time validation to work properly.
```tsx filename="app/blog/[slug]/page.tsx"
```tsx filename="app/blog/[slug]/page.tsx"
// ❌ This will cause an error with Cache Components
The build process only validates code paths that execute with your sample params. If runtime parameters trigger conditional logic that renders branches accessing runtime APIs (like `cookies()`) without Suspense, or dynamic content without Suspense or `use cache`, those will cause runtime errors.
### Option 2: Use a placeholder param
If you don'tknowactualvaluesatbuildtime,youcanuseaplaceholderforvalidation.However,thisdefeatsthepurposeofbuild-timevalidationandshouldbeavoided:
```tsx filename="app/blog/[slug]/page.tsx"
```tsx filename="app/blog/[slug]/page.tsx"
export async function generateStaticParams() {
export async function generateStaticParams() {
// Return a placeholder for build-time validation
// Placeholder only validates one code path
// Real params will be generated at runtime via ISR
return [{ slug: '__placeholder__' }]
return [{ slug: '__placeholder__' }]
}
}
...
@@ -57,13 +61,18 @@ export default async function Page({
...
@@ -57,13 +61,18 @@ export default async function Page({
notFound()
notFound()
}
}
// Your actual page logic
// Real params may trigger code paths
// that access dynamic APIs incorrectly, causing
// runtime errors that cannot be caught by error boundaries