Unverified Commit 6cc51a3b authored by Joseph's avatar Joseph Committed by GitHub

docs: dynamic routes w/ gsP (#86402)

parent c54eda4b
...@@ -158,7 +158,7 @@ A specific type of dynamic data that requires request context, only available wh ...@@ -158,7 +158,7 @@ A specific type of dynamic data that requires request context, only available wh
- [`cookies()`](/docs/app/api-reference/functions/cookies) - User's cookie data - [`cookies()`](/docs/app/api-reference/functions/cookies) - User's cookie data
- [`headers()`](/docs/app/api-reference/functions/headers) - Request headers - [`headers()`](/docs/app/api-reference/functions/headers) - Request headers
- [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) - URL query parameters - [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) - URL query parameters
- [`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.
```tsx filename="page.tsx" ```tsx filename="page.tsx"
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
......
...@@ -67,7 +67,6 @@ export default function BlogPostPage({ ...@@ -67,7 +67,6 @@ export default function BlogPostPage({
```jsx filename="app/blog/[slug]/page.js" switcher ```jsx filename="app/blog/[slug]/page.js" switcher
'use client' 'use client'
import { use } from 'react' import { use } from 'react'
import { useParams } from 'next/navigation'
export default function BlogPostPage({ params }) { export default function BlogPostPage({ params }) {
const { slug } = use(params) const { slug } = use(params)
...@@ -145,6 +144,151 @@ export default async function Page(props: PageProps<'/[locale]'>) { ...@@ -145,6 +144,151 @@ export default async function Page(props: PageProps<'/[locale]'>) {
- Since the `params` prop is a promise. You must use `async`/`await` or React's use function to access the values. - Since the `params` prop is a promise. You must use `async`/`await` or React'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.
```tsx filename="app/blog/[slug]/page.tsx" highlight={5-7,10,22,24}
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: '1' }, { slug: '2' }, { slug: '3' }]
}
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) {
'use cache'
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't be validated at build time:
```tsx filename="app/blog/[slug]/page.tsx"
import { cookies } from 'next/headers'
export async function generateStaticParams() {
return [{ slug: 'public-post' }, { slug: 'hello-world' }]
}
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
}
```
For runtime params not returned by `generateStaticParams`, validation occurs during the first request. In the example above, requests for slugs starting with `private-` will fail because `PrivatePost` accesses `cookies()` without a Suspense boundary. Other runtime params that don't hit the conditional branch will render successfully and be saved to disk for subsequent requests.
To fix this, wrap `PrivatePost` with Suspense:
```tsx filename="app/blog/[slug]/page.tsx" highlight={13-15}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export async function generateStaticParams() {
return [{ slug: 'public-post' }, { slug: 'hello-world' }]
}
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:
```ts filename="app/api/posts/[id]/route.ts" switcher
export async function generateStaticParams() {
const posts: { id: number }[] = await fetch(
'https://api.vercel.app/blog'
).then((res) => res.json())
return posts.map((post) => ({
id: `${post.id}`,
}))
}
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[id]'>
) {
const { id } = await params
const res = await fetch(`https://api.vercel.app/blog/${id}`)
if (!res.ok) {
return Response.json({ error: 'Post not found' }, { status: 404 })
}
const post = await res.json()
return Response.json(post)
}
```
```js filename="app/api/posts/[id]/route.js" switcher
export async function generateStaticParams() {
const posts = await fetch('https://api.vercel.app/blog').then((res) =>
res.json()
)
return posts.map((post) => ({
id: `${post.id}`,
}))
}
export async function GET(request, { params }) {
const { id } = await params
const res = await fetch(`https://api.vercel.app/blog/${id}`)
if (!res.ok) {
return Response.json({ error: 'Post not found' }, { status: 404 })
}
const post = await res.json()
return Response.json(post)
}
```
In this example, route handlers for all blog post IDs returned by `generateStaticParams` will be statically generated at build time. Requests to other IDs will be handled dynamically at request time.
...@@ -334,6 +334,14 @@ export async function GET(request, { params }) { ...@@ -334,6 +334,14 @@ export async function GET(request, { params }) {
| `app/items/[slug]/route.js` | `/items/b` | `Promise<{ slug: 'b' }>` | | `app/items/[slug]/route.js` | `/items/b` | `Promise<{ slug: 'b' }>` |
| `app/items/[slug]/route.js` | `/items/c` | `Promise<{ slug: 'c' }>` | | `app/items/[slug]/route.js` | `/items/c` | `Promise<{ slug: 'c' }>` |
#### 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` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time. The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
`generateStaticParams` can be used with:
- [Pages](/docs/app/api-reference/file-conventions/page) (`page.tsx`/`page.js`)
- [Layouts](/docs/app/api-reference/file-conventions/layout) (`layout.tsx`/`layout.js`)
- [Route Handlers](/docs/app/api-reference/file-conventions/route) (`route.ts`/`route.js`)
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
// 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's empty. Otherwise, the route will be dynamically rendered. > **Good to know:**
>
> - You must always return an array from `generateStaticParams`, even if it's empty. Otherwise, the route will be dynamically rendered.
```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
When using [Cache Components](/docs/app/getting-started/cache-components) with dynamic routes, `generateStaticParams` must return **at least one param**. Empty arrays cause a [build error](/docs/messages/empty-generate-static-params). This allows Cache Components to validate your route doesn't incorrectly access `cookies()`, `headers()`, or `searchParams` 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 with `notFound()`. However, this prevents build time validation from working effectively and may cause runtime errors.
See the [dynamic routes section](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components) for detailed walkthroughs.
### With Route Handlers
You can use `generateStaticParams` with [Route Handlers](/docs/app/api-reference/file-conventions/route) to statically generate API responses at build time:
```ts filename="app/api/posts/[id]/route.ts" switcher
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[id]'>
) {
const { id } = await params
// This will be statically generated for IDs 1, 2, and 3
return Response.json({ id, title: `Post ${id}` })
}
```
```js filename="app/api/posts/[id]/route.js" switcher
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export async function GET(request, { params }) {
const { id } = await params
// This will be statically generated for IDs 1, 2, and 3
return Response.json({ id, title: `Post ${id}` })
}
```
### Route Handlers with Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components), combine with `use cache` for optimal caching:
```ts filename="app/api/posts/[id]/route.ts"
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
async function getPost(id: Promise<string>) {
'use cache'
const resolvedId = await id
const response = await fetch(`https://api.example.com/posts/${resolvedId}`)
return response.json()
}
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[id]'>
) {
const post = await getPost(params.then((p) => p.id))
return Response.json(post)
}
```
See the [Route Handlers documentation](/docs/app/api-reference/file-conventions/route#static-generation-with-generatestaticparams) for more details.
### Disable rendering for unspecified paths ### Disable rendering for unspecified paths
To prevent unspecified paths from being statically rendered at runtime, add the `export const dynamicParams = false` option in a route segment. When this config option is used, only paths provided by `generateStaticParams` will be served, and unspecified routes will 404 or match (in the case of [catch-all routes](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments)). To prevent unspecified paths from being statically rendered at runtime, add the `export const dynamicParams = false` option in a route segment. When this config option is used, only paths provided by `generateStaticParams` will be served, and unspecified routes will 404 or match (in the case of [catch-all routes](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments)).
......
...@@ -212,6 +212,23 @@ export default async function Page({ searchParams }) { ...@@ -212,6 +212,23 @@ export default async function Page({ searchParams }) {
Alternatively you can add a Suspense boundary above the component that is accessing `params` or `searchParams` so Next.js understands what UI should be used when while waiting for this request data to be accessed. Alternatively you can add a Suspense boundary above the component that is accessing `params` or `searchParams` so Next.js understands what UI should be used when while waiting for this request data to be accessed.
#### `generateStaticParams`
For Layout and Page `params`, you can use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) to provide sample values for build-time validation, which allows you to await params directly without Suspense.
```jsx filename="app/blog/[slug]/page.js"
export async function generateStaticParams() {
return [{ slug: 'hello-world' }]
}
export default async function Page({ params }) {
const { slug } = await params // Valid with generateStaticParams
return <div>Blog post: {slug}</div>
}
```
Note that validation is path-dependent. Runtime parameters may trigger conditional branches accessing runtime APIs without Suspense, or dynamic content without Suspense or `use cache`, resulting in errors. See [Dynamic Routes with Cache Components](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components).
### Short-lived Caches ### Short-lived Caches
`"use cache"` allows you to describe a [`cacheLife()`](/docs/app/api-reference/functions/cacheLife) that might be too short to be practical to prerender. The utility of doing this is that it can still describe a non-zero caching time for the client router cache to reuse the cache entry in the browser and it can also be useful for protecting upstream APIs while experiencing high request traffic. `"use cache"` allows you to describe a [`cacheLife()`](/docs/app/api-reference/functions/cacheLife) that might be too short to be practical to prerender. The utility of doing this is that it can still describe a non-zero caching time for the client router cache to reuse the cache entry in the browser and it can also be useful for protecting upstream APIs while experiencing high request traffic.
......
...@@ -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't access dynamic values (like `await cookies()`, `await headers()`, or `await searchParams`) at runtime, which would cause errors. 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't access dynamic values (like `await cookies()`, `await headers()`, or `await searchParams`) at runtime, which would cause errors.
...@@ -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 // This will cause an error with Cache Components
export async function generateStaticParams() { export async function generateStaticParams() {
return [] // Empty array not allowed return [] // Empty array not allowed
} }
// ✅ Return at least one param // Return at least one sample param
export async function generateStaticParams() { export async function generateStaticParams() {
return [{ slug: 'hello-world' }, { slug: 'getting-started' }] return [{ slug: 'hello-world' }, { slug: 'getting-started' }]
} }
``` ```
### Option 2: Use a placeholder param for validation These samples serve dual purposes:
If you don't know the actual values at build time but still want Cache Components, you can return a placeholder param for build-time validation: 1. **Build-time validation**: Verify your route structure is safe
2. **Prerendering**: Generate instant-loading pages for popular routes
> This is not recommended and should only be used if you absolutely need to as it prevents build-time validation from working which will likely cause runtime errors. 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't know actual values at build time, you can use a placeholder for validation. However, this defeats the purpose of build-time validation and should be avoided:
```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
const post = await getPost(slug) const post = await getPost(slug)
return <div>{post.title}</div> return <div>{post.title}</div>
} }
``` ```
Using placeholders provides minimal build-time validation and increases the risk of runtime errors for actual parameter values.
## Useful Links ## Useful Links
- [Cache Components Documentation](https://nextjs.org/docs/beta/app/api-reference/config/next-config-js/cacheComponents) - [Cache Components Documentation](https://nextjs.org/docs/app/getting-started/cache-components)
- [generateStaticParams API Reference](https://nextjs.org/docs/app/api-reference/functions/generate-static-params) - [generateStaticParams API Reference](https://nextjs.org/docs/app/api-reference/functions/generate-static-params)
- [Dynamic Routes with Cache Components](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment