Unverified Commit 7378b51e authored by Joseph's avatar Joseph Committed by GitHub

Backport/docs fixes 16.3 (#97649)

## Summary

- docs: remove experimental note from runtime prefetching (#96615)
- docs: proxy event argument (#96435)
- docs: correction to dynamicParams migration (#96624)
- docs: quote the dynamicParams build error in a blockquote (#96633)
- docs: use relative doc links in instant-navigation error pages
(#96672)
- docs: document ! exclusion and src/ prefix for --debug-build-paths
(#96703)
- docs: instant navigation quick start with an adoption prompt (#96663)
- docs (Skills): stop assuming app/ at the root and port 3000 (#96696)
- docs: present each Skill as steps in the AI agents guide (#96751)
- docs: update redirected links to current targets (#96723)
- docs: add authentication with Cache Components guide and iron-session
example (#95802)
- docs: link View Transitions skill on skills.sh and clarify the example
prompt (#96863)
- Add a `turbopackChunking` documentation page for pages router (#96698)
- docs: add `export const dynamic = 'force-static'` to Route Handlers
example on Static Exports (#96964)
- docs: runtime prefetching -> optimizing prefetching (#96934)
- Fix typo in Data Access Layer section (#87202)
- docs: rename repo to repository for consistency (#87849)
- docs(mdx): fix package name in .md handling section (#97131)
- docs: fix Link prefetch grammar and Client Components wording (#97132)
- docs: align Cache Components authentication guide title (#97143)
- docs: create client-side fetching guide (#96341)
- docs: clarify client cache freshness after hydration (#97180)
- docs: server client and directives (#96145)
- Update authentication diagram URL (#97320)
- docs: align SPA guide reducer example with React conventions (#97341)
- docs: app router reference accuracy (#97477)
- docs: mention Valibot as validation library option in forms guides
(#97468)
- docs: warn when catching permanentRedirect (#97496)
- [docs] fix: grammar typos in linking and navigating guide (#95544)
- docs: rename Vercel Edge Config to Global Config in redirecting guide
(#97456)
- docs: document metadata pagination field (#95509)
- docs: outlining and lcp (#96942)
- docs: adjust interactive app guide (#97558)
- docs: generateMetadata values should be serializable with use cache
(#97551)
- Fix stale cross-references in skills/ (#97566)
- Improve Cache Components sync IO migration guidance (#97572)
- docs: Explicit cache output description (#97548)
- docs: document deploymentId build ID override and Pages Router skew in
16.2 (#97645)
- docs: drop stale Route Handlers restriction from `use cache: private`
(docs part of #97349)
- docs: clarify beforeInteractive placement for root layouts (#97643)
- docs: Adapters entry page lists its children pages twice (#97677)
- docs: correct the upper stale bound for App Shell exclusion in
cacheLife (#97653)
- Improve Partial Prefetching adoption checks (#97637)
- docs: fix parallelRouteKey parameter name in
useSelectedLayoutSegment(s) (#97710)
- docs(adapters): document assetsHashes and routing.middlewareMatchers
(#96536)
- docs: note that response headers must be set before calling handle()
in a custom server (#97693)
- Document catchError for the Pages Router (#97748)
- docs: fix typos and correctness issues in App Router docs (#97823)
- docs: param access on use-server (#97865)
- docs: clarify revalidateTag profile expire semantics (#97836)

---------
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarClaude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
Co-authored-by: 's avatarSam Poder <sampoder@berkeley.edu>
Co-authored-by: 's avatarMasashi Kawafuji <masashikawafuji@proton.me>
Co-authored-by: 's avatarAkseli Palmer <akseli@toddsden.com>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarJarren <sanjose.jarren@gmail.com>
Co-authored-by: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
Co-authored-by: 's avatarPavan Shinde <pavann97@gmail.com>
Co-authored-by: 's avatarReza Karimzadeh <r.karimzadeh1998@gmail.com>
Co-authored-by: 's avatarFabian Hiller <hillerfabian11@gmail.com>
Co-authored-by: 's avatarDavid Alexandru Ilie <david@davidilie.com>
Co-authored-by: 's avatarSean Beirnes <127370575+seanbeirnes@users.noreply.github.com>
Co-authored-by: 's avatarRich Haines <22930449+molebox@users.noreply.github.com>
Co-authored-by: 's avatarKAM <biukam.w@gmail.com>
Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
Co-authored-by: 's avatarJude Gao <jude.gao@vercel.com>
Co-authored-by: 's avatarSaid Nasser <sdnssr001@gmail.com>
Co-authored-by: 's avatarEddy (Frontend Engineer) <101346918+leejpsd@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 528c1cdf
...@@ -158,7 +158,7 @@ You can continue nesting folders to create nested routes. For example, to create ...@@ -158,7 +158,7 @@ You can continue nesting folders to create nested routes. For example, to create
/> />
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
function generateStaticParams() {} export function generateStaticParams() {}
export default function Page() { export default function Page() {
return <h1>Hello, Blog Post Page!</h1> return <h1>Hello, Blog Post Page!</h1>
...@@ -166,7 +166,7 @@ export default function Page() { ...@@ -166,7 +166,7 @@ export default function Page() {
``` ```
```jsx filename="app/blog/[slug]/page.js" switcher ```jsx filename="app/blog/[slug]/page.js" switcher
function generateStaticParams() {} export function generateStaticParams() {}
export default function Page() { export default function Page() {
return <h1>Hello, Blog Post Page!</h1> return <h1>Hello, Blog Post Page!</h1>
...@@ -247,7 +247,7 @@ export default async function BlogPostPage({ params }) { ...@@ -247,7 +247,7 @@ export default async function BlogPostPage({ params }) {
Learn more about [Dynamic Segments](/docs/app/api-reference/file-conventions/dynamic-routes) and the [`params`](/docs/app/api-reference/file-conventions/page#params-optional) props. Learn more about [Dynamic Segments](/docs/app/api-reference/file-conventions/dynamic-routes) and the [`params`](/docs/app/api-reference/file-conventions/page#params-optional) props.
Nested [layouts within Dynamic Segments](/docs/app/api-reference/file-conventions/layout#params-optional), can also access the `params` props. Nested [layouts within Dynamic Segments](/docs/app/api-reference/file-conventions/layout#params-optional) can also access the `params` props.
## Rendering with search params ## Rendering with search params
......
...@@ -158,7 +158,7 @@ Next.js avoids this with client-side transitions using the `<Link>` component. I ...@@ -158,7 +158,7 @@ Next.js avoids this with client-side transitions using the `<Link>` component. I
- Keeping any shared layouts and UI. - Keeping any shared layouts and UI.
- Replacing the current page with the prefetched loading state or a new page if available. - Replacing the current page with the prefetched loading state or a new page if available.
Client-side transitions are what makes a server-rendered apps _feel_ like client-rendered apps. And when paired with [prefetching](#prefetching) and [streaming](#streaming), it enables fast transitions, even for dynamic routes. Client-side transitions make server-rendered apps _feel_ like client-rendered apps. And when paired with [prefetching](#prefetching) and [streaming](#streaming), they enable fast transitions, even for dynamic routes.
Next.js also handles [scrolling to the top of the page](/docs/app/api-reference/components/link#scroll) during client-side transitions. If content scrolls behind a sticky or fixed header after navigation, you can fix this with CSS [`scroll-padding-top`](/docs/app/api-reference/components/link#scroll-offset-with-sticky-headers). Next.js also handles [scrolling to the top of the page](/docs/app/api-reference/components/link#scroll) during client-side transitions. If content scrolls behind a sticky or fixed header after navigation, you can fix this with CSS [`scroll-padding-top`](/docs/app/api-reference/components/link#scroll-offset-with-sticky-headers).
......
...@@ -6,12 +6,15 @@ related: ...@@ -6,12 +6,15 @@ related:
description: Learn more about the APIs mentioned in this page. description: Learn more about the APIs mentioned in this page.
links: links:
- app/api-reference/directives/use-client - app/api-reference/directives/use-client
- app/guides/server-and-client-boundary
--- ---
By default, layouts and pages are [Server Components](https://react.dev/reference/rsc/server-components), which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need interactivity or browser APIs, you can use [Client Components](https://react.dev/reference/rsc/use-client) to layer in functionality. By default, layouts and pages are [Server Components](https://react.dev/reference/rsc/server-components), which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need interactivity or browser APIs, you can use [Client Components](https://react.dev/reference/rsc/use-client) to layer in functionality.
This page explains how Server and Client Components work in Next.js and when to use them, with examples of how to compose them together in your application. This page explains how Server and Client Components work in Next.js and when to use them, with examples of how to compose them together in your application.
> **Good to know:** For an explanation of where each component type runs and how the boundary works, see [The Server and Client Boundary](/docs/app/guides/server-and-client-boundary).
## When to use Server and Client Components? ## When to use Server and Client Components?
The client and server environments have different capabilities. Server and Client Components allow you to run logic in each environment depending on your use case. The client and server environments have different capabilities. Server and Client Components allow you to run logic in each environment depending on your use case.
...@@ -20,7 +23,7 @@ Use **Client Components** when you need: ...@@ -20,7 +23,7 @@ Use **Client Components** when you need:
- [State](https://react.dev/learn/managing-state) and [event handlers](https://react.dev/learn/responding-to-events). E.g. `onClick`, `onChange`. - [State](https://react.dev/learn/managing-state) and [event handlers](https://react.dev/learn/responding-to-events). E.g. `onClick`, `onChange`.
- [Lifecycle logic](https://react.dev/learn/lifecycle-of-reactive-effects). E.g. `useEffect`. - [Lifecycle logic](https://react.dev/learn/lifecycle-of-reactive-effects). E.g. `useEffect`.
- Browser-only APIs. E.g. `localStorage`, `window`, `Navigator.geolocation`, etc. - Browser-only APIs. E.g. `localStorage`, `window`, `navigator.geolocation`, etc.
- [Custom hooks](https://react.dev/learn/reusing-logic-with-custom-hooks). - [Custom hooks](https://react.dev/learn/reusing-logic-with-custom-hooks).
Use **Server Components** when you need: Use **Server Components** when you need:
...@@ -56,12 +59,13 @@ export default async function Page({ ...@@ -56,12 +59,13 @@ export default async function Page({
} }
``` ```
```jsx filename="app/[id]/page.js" highlight={1,12} switcher ```jsx filename="app/[id]/page.js" highlight={1,13} switcher
import LikeButton from '@/app/ui/like-button' import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data' import { getPost } from '@/lib/data'
export default async function Page({ params }) { export default async function Page({ params }) {
const post = await getPost(params.id) const { id } = await params
const post = await getPost(id)
return ( return (
<div> <div>
...@@ -106,7 +110,7 @@ On the server, Next.js uses React's APIs to orchestrate rendering. The rendering ...@@ -106,7 +110,7 @@ On the server, Next.js uses React's APIs to orchestrate rendering. The rendering
> **What is the React Server Component Payload (RSC)?** > **What is the React Server Component Payload (RSC)?**
> >
> The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains: > The RSC Payload is a compact, serialized representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
> >
> - The rendered result of Server Components > - The rendered result of Server Components
> - Placeholders for where Client Components should be rendered and references to their JavaScript files > - Placeholders for where Client Components should be rendered and references to their JavaScript files
...@@ -135,7 +139,7 @@ On subsequent navigations: ...@@ -135,7 +139,7 @@ On subsequent navigations:
### Using Client Components ### Using Client Components
You can create a Client Component by adding the [`"use client"`](https://react.dev/reference/react/use-client) directive at the top of the file, above your imports. You can create a Client Component by adding the [`"use client"`](https://react.dev/reference/rsc/use-client) directive at the top of the file, above your imports.
```tsx filename="app/ui/counter.tsx" highlight={1} switcher ```tsx filename="app/ui/counter.tsx" highlight={1} switcher
'use client' 'use client'
...@@ -183,7 +187,7 @@ See [Interleaving Server and Client Components](/docs/app/getting-started/server ...@@ -183,7 +187,7 @@ See [Interleaving Server and Client Components](/docs/app/getting-started/server
To reduce the size of your client JavaScript bundles, add `'use client'` to specific interactive components instead of marking large parts of your UI as Client Components. To reduce the size of your client JavaScript bundles, add `'use client'` to specific interactive components instead of marking large parts of your UI as Client Components.
For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` is interactive and needs to be a Client Component, however, the rest of the layout can remain a Server Component. For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` needs to be a Client Component, while the rest of the layout can stay a Server Component.
```tsx filename="app/layout.tsx" highlight={12} switcher ```tsx filename="app/layout.tsx" highlight={12} switcher
// Client Component // Client Component
...@@ -261,12 +265,13 @@ export default async function Page({ ...@@ -261,12 +265,13 @@ export default async function Page({
} }
``` ```
```jsx filename="app/[id]/page.js" highlight={1,7} switcher ```jsx filename="app/[id]/page.js" highlight={1,8} switcher
import LikeButton from '@/app/ui/like-button' import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data' import { getPost } from '@/lib/data'
export default async function Page({ params }) { export default async function Page({ params }) {
const post = await getPost(params.id) const { id } = await params
const post = await getPost(id)
return <LikeButton likes={post.likes} /> return <LikeButton likes={post.likes} />
} }
......
...@@ -371,6 +371,8 @@ export default function BlogPage() { ...@@ -371,6 +371,8 @@ export default function BlogPage() {
} }
``` ```
See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating a library cache with the Next.js server and client caches.
## Examples ## Examples
### Sequential data fetching ### Sequential data fetching
......
...@@ -441,7 +441,7 @@ export async function createPost(formData: FormData) { ...@@ -441,7 +441,7 @@ export async function createPost(formData: FormData) {
} }
``` ```
```js filename="app/actions.js" switcher ```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
...@@ -481,7 +481,7 @@ export async function createPost(formData: FormData) { ...@@ -481,7 +481,7 @@ export async function createPost(formData: FormData) {
} }
``` ```
```js filename="app/actions.js" switcher ```js filename="app/lib/actions.js" switcher
'use server' 'use server'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
......
...@@ -47,11 +47,11 @@ The [`use cache`](/docs/app/api-reference/directives/use-cache) directive caches ...@@ -47,11 +47,11 @@ The [`use cache`](/docs/app/api-reference/directives/use-cache) directive caches
- **Data-level**: Cache a function that fetches or computes data (e.g., `getProducts()`, `getUser(id)`) - **Data-level**: Cache a function that fetches or computes data (e.g., `getProducts()`, `getUser(id)`)
- **UI-level**: Cache an entire component or page (e.g., `async function BlogPosts()`) - **UI-level**: Cache an entire component or page (e.g., `async function BlogPosts()`)
A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#runtime-prefetching). A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#prefetching).
> **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies. > **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies.
Arguments and any closed-over values from parent scopes automatically become part of the [cache key](/docs/app/api-reference/directives/use-cache#cache-keys), which means different inputs will produce separate cache entries. See [serialization requirements and constraints](/docs/app/api-reference/directives/use-cache#constraints) for details on what can be cached and how arguments work. Arguments and any values captured from parent scopes automatically become part of the [cache key](/docs/app/api-reference/directives/use-cache#cache-keys), which means different inputs will produce separate cache entries. See [cache output](/docs/app/api-reference/directives/use-cache#cache-output) for what an entry holds, and [serialization requirements and constraints](/docs/app/api-reference/directives/use-cache#constraints) for details on what can be cached and how arguments work.
### Data-level caching ### Data-level caching
...@@ -146,7 +146,7 @@ Without a `<Suspense>` boundary around the uncached read, the dev overlay surfac ...@@ -146,7 +146,7 @@ Without a `<Suspense>` boundary around the uncached read, the dev overlay surfac
> **Good to know:** Each fix card links to a detailed walkthrough with patterns, code samples, and trade-offs. Click a card to dive in. > **Good to know:** Each fix card links to a detailed walkthrough with patterns, code samples, and trade-offs. Click a card to dive in.
{/* xref to the sync io section - that section should also emphaize that these are not random or timestamp sync invokations, in the referenced section */} {/* xref to the sync io section - that section should also emphasize that these are not random or timestamp sync invocations, in the referenced section */}
`<Suspense>` provides a fallback UI while async work completes, but it does not itself opt a component into dynamic rendering. If a component only performs synchronous work, it will complete during prerendering regardless of whether it is wrapped in `<Suspense>`. `<Suspense>` provides a fallback UI while async work completes, but it does not itself opt a component into dynamic rendering. If a component only performs synchronous work, it will complete during prerendering regardless of whether it is wrapped in `<Suspense>`.
## Working with runtime APIs ## Working with runtime APIs
...@@ -197,7 +197,7 @@ A runtime API access without `<Suspense>` surfaces the same **blocking-route** i ...@@ -197,7 +197,7 @@ A runtime API access without `<Suspense>` surfaces the same **blocking-route** i
/> />
</FixCardGrid> </FixCardGrid>
Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#runtime-prefetching). Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#prefetching).
The following section shows an alternative to `use cache: private`: extracting a runtime value and passing it to a shared cached function. The following section shows an alternative to `use cache: private`: extracting a runtime value and passing it to a shared cached function.
...@@ -236,7 +236,7 @@ At request time, `<CachedContent />` executes if no matching cache entry is foun ...@@ -236,7 +236,7 @@ At request time, `<CachedContent />` executes if no matching cache entry is foun
> **Good to know:** Because `<CachedContent />` is gated behind request data, it isn't added to the prerendered static shell. At runtime it's cached [in-memory](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) by default, which doesn't persist across serverless requests, so it may re-evaluate on each request. Reach for [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared caching. > **Good to know:** Because `<CachedContent />` is gated behind request data, it isn't added to the prerendered static shell. At runtime it's cached [in-memory](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) by default, which doesn't persist across serverless requests, so it may re-evaluate on each request. Reach for [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared caching.
With this pattern, [runtime prefetching](#runtime-prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window. With this pattern, [prefetching](#prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window.
## Static, cached, and streaming ## Static, cached, and streaming
...@@ -469,7 +469,7 @@ Next.js requires you to explicitly handle components that can't complete during ...@@ -469,7 +469,7 @@ Next.js requires you to explicitly handle components that can't complete during
### Maximizing the static shell ### Maximizing the static shell
The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and runtime prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches. The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches.
Consider a layout that destructures `params` at the top level: Consider a layout that destructures `params` at the top level:
...@@ -531,17 +531,17 @@ Cache Components shipped in 16.0.0 with verification that direct visits to a rou ...@@ -531,17 +531,17 @@ Cache Components shipped in 16.0.0 with verification that direct visits to a rou
Read the [Instant navigation guide](/docs/app/guides/instant-navigation) for examples and inspection tools. Read the [Instant navigation guide](/docs/app/guides/instant-navigation) for examples and inspection tools.
### Runtime prefetching ### Prefetching
With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default, which already includes static content and the session data derived from `cookies()` and `headers()`. Runtime prefetching extends the prefetch with **URL data**: the `searchParams` and dynamic `params` that vary per destination link. With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default. The App Shell includes static content and session data derived from `cookies()` and `headers()`. To also prefetch cached content that depends on a link's **URL data**, such as `searchParams` or dynamic `params`, set `prefetch={true}` on that link.
With [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) pointing at a [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) route, Next.js renders that route's component tree again at prefetch time, this time with the destination URL resolved. The same rules apply, but more of the tree resolves now that its `searchParams` and `params` are in scope: With [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) pointing at a [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) route, Next.js renders that route's component tree again at prefetch time, this time with the destination URL resolved. The same rules apply, but more of the tree resolves now that its `searchParams` and `params` are in scope:
- [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the runtime prerender - [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the per-link prefetch
- [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser, joining the runtime prerender - [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser as part of the per-link prefetch
- [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the runtime prerender while uncached content streams at request time - [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the prefetched UI while uncached content streams at request time
This generates a **runtime prerender** that extends past the static shell with content the destination URL unlocks. Because it happens during the prefetch, the navigation has nothing to wait on. The cost is a server invocation per prefetchable link. This per-link prefetch includes cached content that resolves after the destination URL is known. It costs a server invocation per prefetchable link.
For example, take a search page that reads `searchParams` from the URL: For example, take a search page that reads `searchParams` from the URL:
...@@ -582,7 +582,7 @@ When a [`<Link>`](/docs/app/api-reference/components/link) to `/search?q=shoes` ...@@ -582,7 +582,7 @@ When a [`<Link>`](/docs/app/api-reference/components/link) to `/search?q=shoes`
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) to understand how `<Link>` prefetching behaves and how to adopt it. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) to understand how `<Link>` prefetching behaves and how to adopt it.
See the [Runtime prefetching guide](/docs/app/guides/runtime-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes. See the [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes.
## Where cached content is stored ## Where cached content is stored
...@@ -590,7 +590,7 @@ A cached function's output is serialized into an **RSC payload**, at build time ...@@ -590,7 +590,7 @@ A cached function's output is serialized into an **RSC payload**, at build time
- **Prerendered HTML.** The payload is rendered to HTML and stored on disk when self-hosting, or in your platform's durable storage behind a CDN. That HTML is the [static shell](#prerendering) at build time and the concrete page after an [ISR](#incremental-static-regeneration) upgrade, with [`revalidate`](/docs/app/api-reference/functions/cacheLife#revalidate) and [`expire`](/docs/app/api-reference/functions/cacheLife#expire) controlling when it's rebuilt. - **Prerendered HTML.** The payload is rendered to HTML and stored on disk when self-hosting, or in your platform's durable storage behind a CDN. That HTML is the [static shell](#prerendering) at build time and the concrete page after an [ISR](#incremental-static-regeneration) upgrade, with [`revalidate`](/docs/app/api-reference/functions/cacheLife#revalidate) and [`expire`](/docs/app/api-reference/functions/cacheLife#expire) controlling when it's rebuilt.
- **Shared store.** By default the result stays in a per-instance, in-memory store that is ephemeral on serverless. [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) moves it to a durable [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) shared across instances, a network roundtrip that pays off only at a **high hit rate**. - **Shared store.** By default the result stays in a per-instance, in-memory store that is ephemeral on serverless. [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) moves it to a durable [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) shared across instances, a network roundtrip that pays off only at a **high hit rate**.
- **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#runtime-prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here. - **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here.
> **Good to know:** An [App Shell](/docs/app/glossary#app-shell) that reads `cookies()` or `headers()` is session-specific, cached per session on the client rather than in the shared server cache. > **Good to know:** An [App Shell](/docs/app/glossary#app-shell) that reads `cookies()` or `headers()` is session-specific, cached per session on the client rather than in the shared server cache.
......
...@@ -221,14 +221,14 @@ export default function Page() { ...@@ -221,14 +221,14 @@ export default function Page() {
To start using CSS Modules, create a new file with the extension `.module.css` and import it into any component inside the `pages` directory: To start using CSS Modules, create a new file with the extension `.module.css` and import it into any component inside the `pages` directory:
```css filename="/styles/blog.module.css" ```css filename="styles/blog.module.css"
.blog { .blog {
padding: 24px; padding: 24px;
} }
``` ```
```tsx filename="pages/blog/index.tsx" switcher ```tsx filename="pages/blog/index.tsx" switcher
import styles from './blog.module.css' import styles from '@/styles/blog.module.css'
export default function Page() { export default function Page() {
return <main className={styles.blog}></main> return <main className={styles.blog}></main>
...@@ -236,7 +236,7 @@ export default function Page() { ...@@ -236,7 +236,7 @@ export default function Page() {
``` ```
```jsx filename="pages/blog/index.js" switcher ```jsx filename="pages/blog/index.js" switcher
import styles from './blog.module.css' import styles from '@/styles/blog.module.css'
export default function Page() { export default function Page() {
return <main className={styles.blog}></main> return <main className={styles.blog}></main>
...@@ -299,7 +299,7 @@ export default function RootLayout({ children }) { ...@@ -299,7 +299,7 @@ export default function RootLayout({ children }) {
Import the stylesheet in the `pages/_app.js` file to apply the styles to **every route** in your application: Import the stylesheet in the `pages/_app.js` file to apply the styles to **every route** in your application:
```tsx filename="pages/_app.js" ```jsx filename="pages/_app.js"
import '@/styles/global.css' import '@/styles/global.css'
export default function MyApp({ Component, pageProps }) { export default function MyApp({ Component, pageProps }) {
......
...@@ -257,7 +257,7 @@ The more specific image will take precedence over any OG images above it in the ...@@ -257,7 +257,7 @@ The more specific image will take precedence over any OG images above it in the
The [`ImageResponse` constructor](/docs/app/api-reference/functions/image-response) allows you to generate dynamic images using JSX and CSS. This is useful for OG images that depend on data. The [`ImageResponse` constructor](/docs/app/api-reference/functions/image-response) allows you to generate dynamic images using JSX and CSS. This is useful for OG images that depend on data.
For example, to generate a unique OG image for each blog post, add a `opengraph-image.tsx` file inside the `blog` folder, and import the `ImageResponse` constructor from `next/og`: For example, to generate a unique OG image for each blog post, add an `opengraph-image.tsx` file inside the `blog/[slug]` folder, and import the `ImageResponse` constructor from `next/og`:
```tsx filename="app/blog/[slug]/opengraph-image.tsx" switcher ```tsx filename="app/blog/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
......
...@@ -81,7 +81,7 @@ Next.js can be adapted to run on different platforms to support their infrastruc ...@@ -81,7 +81,7 @@ Next.js can be adapted to run on different platforms to support their infrastruc
Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/adapters/testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters). Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/adapters/testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters).
- [Vercel](https://vercel.com/docs/frameworks/nextjs) - [Vercel](https://vercel.com/docs/frameworks/full-stack/nextjs)
- [Bun](https://bun.com/docs/guides/ecosystem/nextjs) - [Bun](https://bun.com/docs/guides/ecosystem/nextjs)
Cloudflare and Netlify are working on verified adapters built on the Adapter API. In the meantime, they offer their own Next.js integrations (see below). Cloudflare and Netlify are working on verified adapters built on the Adapter API. In the meantime, they offer their own Next.js integrations (see below).
......
...@@ -7,14 +7,14 @@ related: ...@@ -7,14 +7,14 @@ related:
description: Learn more about prefetching and instant navigations. description: Learn more about prefetching and instant navigations.
links: links:
- app/guides/instant-navigation - app/guides/instant-navigation
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
- app/api-reference/config/next-config-js/partialPrefetching - app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/file-conventions/route-segment-config/prefetch - app/api-reference/file-conventions/route-segment-config/prefetch
--- ---
[Partial Prefetching](/docs/app/glossary#partial-prefetching) changes what a `<Link>` downloads for a Cache Components route. With Partial Prefetching enabled, a `<Link>` prefetches the route's [App Shell](/docs/app/glossary#app-shell): its static content and the cached content that doesn't depend on the URL. Next.js builds one App Shell per route and reuses it for every link to that route, rather than prefetching each link separately as it did before. [Partial Prefetching](/docs/app/glossary#partial-prefetching) changes what a `<Link>` downloads for a Cache Components route. With Partial Prefetching enabled, a `<Link>` prefetches the route's [App Shell](/docs/app/glossary#app-shell): its static content and the cached content that doesn't depend on the URL. Next.js builds one App Shell per route and reuses it for every link to that route, rather than prefetching each link separately as it did before.
To prefetch more than the App Shell, a link can opt into [runtime prefetching](/docs/app/guides/runtime-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves the per-link runtime data (`params`, `searchParams`, and the full URL) and the cached content behind it. To prefetch more than the App Shell, a link can opt into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves URL-specific content that depends on `params`, `searchParams`, or the full URL.
Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-navigation) insights in development, naming the link or route to change. Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-navigation) insights in development, naming the link or route to change.
...@@ -65,11 +65,11 @@ After enabling the flag, every `<Link>` prefetches its destination's App Shell, ...@@ -65,11 +65,11 @@ After enabling the flag, every `<Link>` prefetches its destination's App Shell,
## What changes for `<Link>` ## What changes for `<Link>`
| `<Link>` prop | Before (Cache Components default) | After Partial Prefetching | | `<Link>` prop | Before (Cache Components default) | After Partial Prefetching |
| ----------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | ----------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. | | `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. |
| `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus per-link runtime data through [runtime prefetching](/docs/app/guides/runtime-prefetching) when `/x` reads it. | | `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus URL-specific content through [per-link prefetching](/docs/app/guides/optimizing-prefetching) when `/x` reads it. |
| `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. | | `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. |
The App Shell is shared across every link to a given route, regardless of dynamic params, so rendering many `<Link>`s to the same destination doesn't multiply the work. The App Shell is shared across every link to a given route, regardless of dynamic params, so rendering many `<Link>`s to the same destination doesn't multiply the work.
...@@ -79,13 +79,13 @@ Each `<Link prefetch={true}>` used to prefetch its destination's dynamic content ...@@ -79,13 +79,13 @@ Each `<Link prefetch={true}>` used to prefetch its destination's dynamic content
> **Good to know**: `cookies()` and `headers()` don't tie a prefetch to a URL. They vary per session, not per link, so the App Shell still carries session content. Only `params` and `searchParams` are [URL data](/docs/app/glossary#url-data), which varies per link and can't be included in the shared App Shell. > **Good to know**: `cookies()` and `headers()` don't tie a prefetch to a URL. They vary per session, not per link, so the App Shell still carries session content. Only `params` and `searchParams` are [URL data](/docs/app/glossary#url-data), which varies per link and can't be included in the shared App Shell.
| Destination | Recommendation | | Destination | Recommendation |
| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. | | [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. |
| [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. | | [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. |
| [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. | | [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. |
| [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}`, and prefetch the content later with runtime prefetching. | | [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}` to resolve the content ahead of the click. |
| [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. | | [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. |
### Static or cached content ### Static or cached content
...@@ -148,7 +148,7 @@ export default async function Page() { ...@@ -148,7 +148,7 @@ export default async function Page() {
### Session content ### Session content
Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/runtime-prefetching#session-data-resolves-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links: Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/optimizing-prefetching#include-session-data-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links:
```tsx filename="app/dashboard/page.tsx" switcher ```tsx filename="app/dashboard/page.tsx" switcher
// Before // Before
...@@ -319,6 +319,8 @@ The per-route `prefetch = 'partial'` exports are now redundant. Remove them in o ...@@ -319,6 +319,8 @@ The per-route `prefetch = 'partial'` exports are now redundant. Remove them in o
npx @next/codemod@canary remove-partial-prefetch ./app npx @next/codemod@canary remove-partial-prefetch ./app
``` ```
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
The codemod removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place. The codemod removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place.
## Auditing routes for URL data ## Auditing routes for URL data
...@@ -435,7 +437,7 @@ Everything outside the boundary stays in the shared App Shell, and only the URL- ...@@ -435,7 +437,7 @@ Everything outside the boundary stays in the shared App Shell, and only the URL-
## Prefetching URL data ## Prefetching URL data
Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Runtime prefetching](/docs/app/guides/runtime-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`: Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`:
```tsx filename="app/search/page.tsx" switcher ```tsx filename="app/search/page.tsx" switcher
// Before - the results stream in after navigation // Before - the results stream in after navigation
...@@ -535,4 +537,4 @@ export default function Page({ searchParams }) { ...@@ -535,4 +537,4 @@ export default function Page({ searchParams }) {
} }
``` ```
The [runtime prefetching guide](/docs/app/guides/runtime-prefetching) covers when the cost pays off and the caching patterns behind runtime reads. The [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) covers when the cost pays off and the caching patterns behind runtime reads.
...@@ -180,7 +180,13 @@ After every edit, verify the page still works at runtime using the next-dev-loop ...@@ -180,7 +180,13 @@ After every edit, verify the page still works at runtime using the next-dev-loop
### `next-cache-components-adoption` ### `next-cache-components-adoption`
The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill turns on [Cache Components](/docs/app/getting-started/caching) and resolves blocking routes until the app builds. The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill migrates an app to [Cache Components](/docs/app/getting-started/caching):
1. Turns the flag on and finds the routes that can't prerender.
2. Fixes them one feature at a time, checking in with you before moving on.
3. Confirms a feature against `next dev` and `next build` before leaving it.
You choose whether the work lands as a series of PRs or stays on one branch.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-adoption npx skills add vercel/next.js --skill next-cache-components-adoption
...@@ -194,21 +200,33 @@ Adopt Cache Components in this project using the next-cache-components-adoption ...@@ -194,21 +200,33 @@ Adopt Cache Components in this project using the next-cache-components-adoption
### `next-cache-components-optimizer` ### `next-cache-components-optimizer`
The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill maximizes the meaningful UI available on an exact navigation and guards it with an `@next/playwright` `instant()` test. The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill takes a target route or set of routes and works toward the UI you want on screen at click time:
1. Writes a failing [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test for the UI you named.
2. Refactors the route until it passes, often by moving a data read below a `<Suspense>` boundary.
3. Commits the passing test with the refactoring, so it catches future regressions.
It needs a route that already builds with [Cache Components](/docs/app/getting-started/caching).
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-optimizer npx skills add vercel/next.js --skill next-cache-components-optimizer
``` ```
For example, give the agent this prompt: Then give the agent a prompt like:
```prompt ```prompt
Make the navigation to `/settings` instant using the next-cache-components-optimizer Skill. Make the navigation from /settings to /dashboard instant using the next-cache-components-optimizer Skill. The header and the project list should be part of the instant UI.
``` ```
### `next-partial-prefetching-adoption` ### `next-partial-prefetching-adoption`
The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill turns on [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) and resolves its insights until all routes reuse a shared App Shell. The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill moves an app onto [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), where links share one App Shell:
1. Audits the existing `<Link prefetch={true}>` calls with you.
2. Turns the flag on and resolves the insights it surfaces.
3. Marks the routes whose URL data might be worth prefetching later.
It needs [Cache Components](/docs/app/getting-started/caching) already adopted.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-adoption npx skills add vercel/next.js --skill next-partial-prefetching-adoption
......
---
title: How to implement authentication with Cache Components
nav_title: Authentication with Cache Components
description: 'Learn how to read the user session, show authenticated UI without slowing down the page, and cache data derived from the session when Cache Components is enabled.'
related:
title: Next Steps
description: Learn more about authentication, caching, and prefetching in Next.js.
links:
- app/guides/authentication
- app/getting-started/caching
- app/getting-started/fetching-data
- app/guides/optimizing-prefetching
- app/api-reference/directives/use-cache-private
- app/api-reference/functions/cacheTag
- app/api-reference/config/next-config-js/cacheComponents
---
With [Cache Components](/docs/app/getting-started/caching) enabled, a session read happens at request time, so it can't be prerendered into the static shell. Authenticated UI streams in behind a `<Suspense>` boundary instead, and data derived from the session can still be cached.
The examples use [iron-session](https://github.com/vvo/iron-session) for encrypted cookie sessions, but the patterns apply to any session or authentication library. For a complete, runnable version, see the [with-iron-session-cache-components example](https://github.com/vercel/next.js/tree/canary/examples/with-iron-session-cache-components).
## Prerequisites
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents):
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
```
This guide covers code patterns for authentication with Cache Components: reading the session at request time, streaming authenticated UI, and caching session-derived data. It assumes you're comfortable with Cache Components (if not, read [Caching](/docs/app/getting-started/caching) first) and that you already have a session set on login.
For the fundamentals this builds on, we recommend two guides:
- [Authentication](/docs/app/guides/authentication) covers sign-up, login, session management, authorization, and the Data Access Layer.
- [Data Security](/docs/app/guides/data-security) covers keeping data access on the server and sensitive data off the client.
## Migrating an existing app
With Cache Components enabled, instant navigation validation flags every route that reads the session, because a request read can't be prerendered into the static shell. You don't have to resolve them all before shipping. Set [`export const instant = false`](/docs/app/guides/instant-navigation#opting-out) on the page or layout to let it keep blocking on the server, then adopt the patterns below one route at a time. For the full migration workflow, see [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components#following-validation).
## Step 1: Read the current user
Reading the current user reads the session cookie, then looks the user up. A request read can't be part of the static shell, so it always sits behind a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary and streams in on every navigation.
Because a user session is valid for a period of time, adding a cache lifetime lets the framework prefetch that content ahead of time.
The server-side directives can't give it that lifetime, though: neither a plain [`use cache`](/docs/app/api-reference/directives/use-cache) nor [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) can call `cookies()`, and you can't [extract the value and pass it in](/docs/app/getting-started/caching#passing-runtime-values-to-cached-functions) either, because:
- A session helper reads the cookie deep inside its own code, so there's nothing to lift out.
- Validating it compares a token's expiry against the current time (iron-session's `unsealData` rejects an expired seal), so the read is request- and time-dependent.
That's what [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) is for: it reads `cookies()` and `headers()` directly, keeping the result in the browser only, never on the server.
A private scope stays in the browser, so it never caches on the server. To cache on the server instead, extract a value (the `userId`, for example) and pass it into a plain [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote). The same pattern caches data derived from the session, covered in [Step 4](#step-4-cache-session-derived-data).
```tsx filename="lib/session.ts"
import 'server-only'
import { cookies } from 'next/headers'
import { sealData, unsealData } from 'iron-session'
export type SessionData = {
userId?: string
}
const COOKIE_NAME = 'app_session'
const password = process.env.SESSION_PASSWORD!
export async function getSession(): Promise<SessionData> {
const cookie = (await cookies()).get(COOKIE_NAME)?.value
if (!cookie) {
return {}
}
return unsealData<SessionData>(cookie, { password })
}
```
```tsx filename="lib/auth.ts"
import 'server-only'
import { redirect } from 'next/navigation'
import { getSession } from './session'
import { findUserById } from './data'
export type User = {
id: string
name: string
}
export async function getCurrentUser(): Promise<User> {
'use cache: private'
const { userId } = await getSession()
if (!userId) {
redirect('/login')
}
const user = await findUserById(userId)
if (!user) {
redirect('/login')
}
return { id: user.id, name: user.name }
}
```
The `redirect()` calls throw to interrupt rendering rather than return a value, so they aren't cached. Only a resolved user is.
> **Good to know:** `use cache: private` accepts `cookies()`, `headers()`, and `searchParams`, but not [`connection()`](/docs/app/api-reference/functions/connection). See [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) for the full list.
## Step 2: Show the user without blocking the page
A component that reads the session must sit behind a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary. With Cache Components, reading `cookies()` outside a boundary is a build error. The boundary is also what keeps the rest of the page fast. Anything outside it prerenders into the [static shell](/docs/app/getting-started/caching#prerendering) and loads instantly, as long as it's static or wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache) and doesn't read runtime data of its own. Only the section behind the boundary waits for the request.
```tsx filename="app/page.tsx"
import { Suspense } from 'react'
import { getCurrentUser } from '@/lib/auth'
import { getAnnouncements } from '@/lib/data'
export default function Page() {
return (
<main>
{/* Cached, so it prerenders into the static shell */}
<Announcements />
{/* Reads the session, so it streams in behind the boundary */}
<Suspense fallback={<p>Loading your dashboard…</p>}>
<Dashboard />
</Suspense>
</main>
)
}
async function Announcements() {
'use cache'
const announcements = await getAnnouncements()
return (
<ul>
{announcements.map((announcement) => (
<li key={announcement}>{announcement}</li>
))}
</ul>
)
}
async function Dashboard() {
const user = await getCurrentUser()
return <h1>Welcome, {user.name}</h1>
}
```
Keep the session read out of a layout's top level, too. A top-level `await` on the session in a layout holds the whole segment, including `{children}`, behind that request, so push it into a component inside a boundary. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down).
> **Good to know:** `getCurrentUser` reads the session, checks it, and returns a narrow user. Centralizing those reads in one function is the [Data Access Layer](/docs/app/guides/authentication#creating-a-data-access-layer-dal) pattern.
## Step 3: Share the user across components
You don't have to read the session again in every component that needs the user. Read it once, then hand it to as many Server and Client Components as you like from inside the same boundary.
Server Components can call `getCurrentUser()` directly. To reach Client Components without prop drilling, create the promise once, pass it through context, and unwrap it with [`use()`](https://react.dev/reference/react/use). For the general pattern, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider). Because `getCurrentUser` reads the request, create its promise inside the Suspense boundary, not at the top of a layout.
```tsx filename="app/user-provider.tsx"
'use client'
import { createContext, use } from 'react'
import type { ReactNode } from 'react'
import type { User } from '@/lib/auth'
const UserContext = createContext<Promise<User> | null>(null)
export function UserProvider({
userPromise,
children,
}: {
userPromise: Promise<User>
children: ReactNode
}) {
return <UserContext value={userPromise}>{children}</UserContext>
}
export function useUser() {
const userPromise = use(UserContext)
if (!userPromise) {
throw new Error('useUser must be used within a UserProvider')
}
return use(userPromise)
}
```
The Server Component behind the boundary creates the promise and hands it to the provider without awaiting it. Each consumer then resolves it behind its own boundary, so the shared chrome renders without waiting on the session:
```tsx filename="app/page.tsx"
function Dashboard() {
const userPromise = getCurrentUser()
return (
<UserProvider userPromise={userPromise}>
<Suspense fallback={<span>Loading…</span>}>
<UserBadge />
</Suspense>
</UserProvider>
)
}
```
Client Components call `useUser()` to get the current user. Because `use()` suspends until the promise resolves, keep the component behind a `<Suspense>` boundary:
```tsx filename="app/user-badge.tsx"
'use client'
import { useUser } from './user-provider'
export function UserBadge() {
const user = useUser()
return <span>Signed in as {user.name}</span>
}
```
> **Good to know:** Expose only what the client needs. The `getCurrentUser` helper returns a narrow `{ id, name }` rather than the raw session. To keep sensitive fields from reaching the client, see [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue).
## Step 4: Cache session-derived data
Now that you have the user, you can cache the data you fetch for them in one of two ways. Passing the user id into a plain [`use cache`](/docs/app/api-reference/directives/use-cache) function keeps the result on the server, keyed by the id (it becomes part of the [cache key](/docs/app/api-reference/directives/use-cache#cache-keys)), where a [`cacheTag`](/docs/app/api-reference/functions/cacheTag) can invalidate it later. Reading it inside a [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) scope keeps it in the browser only, never on the server, which matters when requirements forbid storing certain data server-side, even ephemerally. The example passes the id, since these notes are tagged and refreshed when they change.
A plain `use cache` scope can't read `cookies()`, so the exported function resolves the user and passes just the id to the cached function:
```tsx filename="lib/data.ts"
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { getCurrentUser } from './auth'
export async function getNotes() {
const user = await getCurrentUser()
return getNotesByUserId(user.id)
}
async function getNotesByUserId(userId: string) {
'use cache'
cacheTag(`notes:${userId}`)
cacheLife('minutes')
return db.query.notes.findMany({
where: (notes, { eq }) => eq(notes.userId, userId),
})
}
```
Keep `getNotesByUserId` unexported so a caller can't request another user's notes by passing a different id. Resolving the user inside the exported getter is what makes that safe. See [Data Security](/docs/app/guides/data-security#data-access-layer).
Call it from a Server Component that renders the notes. There's no user id to pass, and the `getCurrentUser()` call inside the getter hits the private cache, so the session isn't read again:
```tsx filename="app/page.tsx"
async function Notes() {
const notes = await getNotes()
// ...
}
```
> **Good to know: cache keys and tags are stored in plain text.** A cached function's arguments and captured variables are serialized into its cache key, and `cacheTag` values are stored as written. Neither is hashed: the default cache holds them as plain-text map keys and tag lists, and a [remote cache](/docs/app/api-reference/directives/use-cache-remote) receives them the same way. Key and tag on a stable identifier like the user id, and keep secrets and sensitive personal data (tokens, passwords, raw emails) out of arguments and tags.
On the server, plain `use cache` keeps the entry in memory as a best effort: it's evicted under pressure and, in serverless, doesn't persist across instances. If that data must survive across instances and requests, opt into [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared storage, where [the cache key you choose](/docs/app/api-reference/directives/use-cache-remote#cache-key-considerations) drives your hit rate.
## Step 5: Update session-derived data
When a [Server Action](/docs/app/getting-started/mutating-data) changes a user's data, call [`updateTag`](/docs/app/api-reference/functions/updateTag) with the same tag to refresh the cached entry. Re-read the session inside the action so it authorizes itself rather than trusting the client. See [authentication with Server Actions](/docs/app/guides/authentication#server-actions) for why this matters.
```ts filename="app/actions.ts"
'use server'
import { redirect } from 'next/navigation'
import { updateTag } from 'next/cache'
import { getSession } from '@/lib/session'
import { saveNote } from '@/lib/data'
export async function addNote(formData: FormData) {
const { userId } = await getSession()
if (!userId) {
redirect('/login')
}
const note = String(formData.get('note') ?? '').trim()
if (note) {
await saveNote(userId, note)
updateTag(`notes:${userId}`)
}
}
```
## Step 6: Make authenticated navigations instant
Cached reads already have a lifetime, so this mostly happens on its own. A `use cache: private` scope uses the [`default` profile](/docs/app/api-reference/functions/cacheLife#preset-cache-profiles) (a five-minute `stale`) unless you set one, and a route that reads the session produces a per-session [App Shell](/docs/app/glossary#app-shell) with the authenticated content, prefetched and cached per session. Navigations to it are already instant.
Two things keep it that way:
- If you tune the lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife), keep `stale` at 30 seconds or more. Below that, the scope drops out of prefetching. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior).
- A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link data ahead of the click.
```tsx filename="app/page.tsx"
<Link href={`/notes/${note.id}`} prefetch={true}>
{note.text}
</Link>
```
The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: that prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item.
## Common pitfalls
- **Reading `cookies()` or `headers()` inside a plain `use cache` function.** This throws. Read the request outside and pass the value in, or use `use cache: private`.
- **Putting secrets or personal data in cache keys or tags.** Arguments and `cacheTag` values are stored in plain text. Key and tag on a stable identifier, not on sensitive input.
- **Trusting the client for authorization.** UI checks hide elements, but they don't protect data. Re-verify the session in every Server Action and [Route Handler](/docs/app/api-reference/file-conventions/route), close to the data. See [Authorization](/docs/app/guides/authentication#authorization).
...@@ -16,14 +16,16 @@ This diagram shows the authentication flow using React and Next.js features: ...@@ -16,14 +16,16 @@ This diagram shows the authentication flow using React and Next.js features:
<Image <Image
alt="Diagram showing the authentication flow with React and Next.js features" alt="Diagram showing the authentication flow with React and Next.js features"
srcLight="/docs/light/authentication-overview.png" srcLight="/docs/light/authentication-overview-new.png"
srcDark="/docs/dark/authentication-overview.png" srcDark="/docs/dark/authentication-overview-new.png"
width="1600" width="1600"
height="1383" height="1383"
/> />
The examples on this page walk through basic username and password auth for educational purposes. While you can implement a custom auth solution, for increased security and simplicity, we recommend using an authentication library. These offer built-in solutions for authentication, session management, and authorization, as well as additional features such as social logins, multi-factor authentication, and role-based access control. You can find a list in the [Auth Libraries](#auth-libraries) section. The examples on this page walk through basic username and password auth for educational purposes. While you can implement a custom auth solution, for increased security and simplicity, we recommend using an authentication library. These offer built-in solutions for authentication, session management, and authorization, as well as additional features such as social logins, multi-factor authentication, and role-based access control. You can find a list in the [Auth Libraries](#auth-libraries) section.
> **Good to know:** With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, reading the session and caching per-user data follow specific rules. See [Authentication with Cache Components](/docs/app/guides/authentication-with-cache-components).
## Authentication ## Authentication
<AppOnly> <AppOnly>
...@@ -98,7 +100,7 @@ export async function signup(formData) {} ...@@ -98,7 +100,7 @@ export async function signup(formData) {}
#### 2. Validate form fields on the server #### 2. Validate form fields on the server
Use the Server Action to validate the form fields on the server. If your authentication provider doesn't provide form validation, you can use a schema validation library like [Zod](https://zod.dev/) or [Yup](https://github.com/jquense/yup). Use the Server Action to validate the form fields on the server. If your authentication provider doesn't provide form validation, you can use a schema validation library like [Zod](https://zod.dev/), [Valibot](https://valibot.dev/) or [Yup](https://github.com/jquense/yup).
Using Zod as an example, you can define a form schema with appropriate error messages: Using Zod as an example, you can define a form schema with appropriate error messages:
...@@ -1363,7 +1365,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across ...@@ -1363,7 +1365,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across
If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern. If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern.
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache). Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a context provider. For that pattern, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider), and use React's [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to keep sensitive session fields from reaching the client.
#### Auth checks in page components #### Auth checks in page components
...@@ -1550,60 +1552,6 @@ export async function GET() { ...@@ -1550,60 +1552,6 @@ export async function GET() {
The example above demonstrates a Route Handler with a two-tier security check. It first checks for an active session, and then verifies if the logged-in user is an 'admin'. The example above demonstrates a Route Handler with a two-tier security check. It first checks for an active session, and then verifies if the logged-in user is an 'admin'.
## Context Providers
Using context providers for auth works due to [interleaving](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components). However, React `context` is not supported in Server Components, making them only applicable to Client Components.
This works, but any child Server Components will be rendered on the server first, and will not have access to the context provider’s session data:
```tsx filename="app/layout.tsx" switcher
import { ContextProvider } from 'auth-lib'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<ContextProvider>{children}</ContextProvider>
</body>
</html>
)
}
```
```tsx filename="app/ui/profile.tsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
```jsx filename="app/ui/profile.jsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
If session data is needed in Client Components (e.g. for client-side data fetching), use React’s [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to prevent sensitive session data from being exposed to the client.
For the general pattern of passing server-fetched data through context and reading it with `use()`, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
</AppOnly> </AppOnly>
<PagesOnly> <PagesOnly>
......
...@@ -108,7 +108,7 @@ export const dynamic = 'auto' ...@@ -108,7 +108,7 @@ export const dynamic = 'auto'
<details> <details>
<summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary> <summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary>
By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any Request-time APIs are used and **will not cache** `fetch` requests that are discovered **after** Request-time APIs are used. A `fetch` request that sets no `cache` option is fetched once during `next build` if it is reachable **before** any Request-time APIs are used, because the route is prerendered up to that point. Requests discovered **after** a Request-time API run on every request.
`fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page. `fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page.
......
...@@ -74,7 +74,7 @@ These headers can be omitted in specific cases without causing protocol errors. ...@@ -74,7 +74,7 @@ These headers can be omitted in specific cases without causing protocol errors.
**When `next-router-prefetch` is present, preserve both the prefetch header and the `_rsc` search parameter.** For prefetch flows, `_rsc` is a required cache-busting discriminator and should be treated as mandatory. **When `next-router-prefetch` is present, preserve both the prefetch header and the `_rsc` search parameter.** For prefetch flows, `_rsc` is a required cache-busting discriminator and should be treated as mandatory.
**The `_rsc` search parameter** must be included in the cache key. It distinguishes response variants (HTML vs. RSC, different prefetch types). Ensure your CDN does not strip query parameters from cache keys, as some CDNs do this by default. By default, when a RSC request arrives without the correct `_rsc` value, the server responds with a **307 redirect** to the URL with the correct hash. This behavior can be disabled by setting `experimental.validateRSCRequestHeaders` to `false`. CDNs should follow this redirect. Platforms that compute the hash upstream can rewrite requests to include the correct `_rsc` before forwarding to avoid an extra round trip. **The `_rsc` search parameter** must be included in the cache key. It distinguishes response variants (HTML vs. RSC, different prefetch types). Ensure your CDN does not strip query parameters from cache keys, as some CDNs do this by default. By default, when an RSC request arrives without the correct `_rsc` value, the server responds with a **307 redirect** to the URL with the correct hash. This behavior can be disabled by setting `experimental.validateRSCRequestHeaders` to `false`. CDNs should follow this redirect. Platforms that compute the hash upstream can rewrite requests to include the correct `_rsc` before forwarding to avoid an extra round trip.
> **Good to know:** Today, `next-url` is included in the `_rsc` hash even during static prefetches. This means you cannot safely ignore it under the current scheme without potentially getting cache misses. The pathname-based direction described below resolves this gap. > **Good to know:** Today, `next-url` is included in the `_rsc` hash even during static prefetches. This means you cannot safely ignore it under the current scheme without potentially getting cache misses. The pathname-based direction described below resolves this gap.
......
---
title: Client-side data fetching
description: Fetch data in Client Components with a data-fetching library, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/guides/interactive-apps
- app/getting-started/caching
---
Many apps can provide responsive interactions without a client data-fetching library. If a Client Component only needs to read server data once, [pass it a Promise and unwrap it with React's `use()`](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api).
This avoids adding a library for data that never revalidates on the client. See [Building interactive apps](/docs/app/guides/interactive-apps) for patterns using Server Functions, transitions, optimistic UI, and pending feedback.
Use a client data-fetching library such as [SWR](https://swr.vercel.app), [TanStack Query](https://tanstack.com/query), or [Apollo Client](https://www.apollographql.com/docs/react) when Client Components need a shared browser cache. These libraries can add focus revalidation, interval polling, request deduplication, or optimistic updates across components.
## Choose a client fetching pattern
First decide whether the initial view needs data from the server or can wait for a browser request after hydration. Client data-fetching libraries support three common patterns:
| Pattern | SWR | TanStack Query | When data becomes available |
| ----------------------- | ------------------------------ | --------------------- | -------------------------------------- |
| Inline loading states | `useSWR` | `useQuery` | Browser request after hydration |
| Suspense loading states | `useSWR` with `suspense: true` | `useSuspenseQuery` | Browser request after hydration |
| Provided by the server | `<SWRConfig fallback>` | `<HydrationBoundary>` | Initial render or streamed from server |
Use inline loading states when each component should render its own loading UI. Use [Suspense](/docs/app/getting-started/fetching-data#streaming) to define loading UI at a boundary and coordinate which parts of the interface reveal together or progressively. For client-only fetching, choose the pattern that matches the loading experience you want. Suspense coordinates rendering, while the data library and component structure determine when requests start.
For browser-driven interactions such as autocomplete, you can use either client-only pattern. The initial result waits for hydration and a browser request, which is often the right tradeoff for data that is not needed until an interaction.
Provide initial data from a [Server Component](/docs/app/getting-started/server-and-client-components) when the server knows what the initial render needs. The value can be included in the initial render or streamed through Suspense. The library receives it in the React Server Component payload and can continue managing it in the browser.
## Cache server data with Cache Components (optional)
Providing initial data and caching it on the server are independent choices. Add Cache Components when the server read or rendered view should be reused. When both are enabled, three cache layers can hold related data:
| Layer | What it stores | Freshness control |
| ---------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Next.js server cache | Cached data and Server Component output | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `revalidate` and `expire` |
| Next.js client cache | React Server Component payloads for visited and prefetched routes | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` |
| Client data-fetching library | Browser data stored under an SWR key or TanStack query key | The library's revalidation options and mutations |
Next.js [prefetching](/docs/app/guides/prefetching) can place a route's React Server Component payload in the client cache before navigation.
The cache layers keep independent freshness policies and do not need matching durations. Cache identities and mutation invalidation must stay coordinated across layers.
## Coordinate mutations
Server Components, data-fetching libraries, and mutations manage different parts of the data flow:
- **Server Components** provide the initial data, scoped to the segment that owns it.
- **The data-fetching library** stores the browser value under a shared cache identity.
- **Mutations** can update the browser cache immediately and invalidate cached server data so the next render can read a fresh value.
An optimistic update should restore the previous browser value if the write fails. If the server read is not cached, there is no server tag to invalidate.
After a mutation, invalidate any cached server read that provided the initial data:
| Method | Use when | Next server read |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------ |
| [`updateTag(tag)`](/docs/app/api-reference/functions/updateTag) | A Server Action must make its update visible immediately | Waits for fresh data |
| [`revalidateTag(tag, 'max')`](/docs/app/api-reference/functions/revalidateTag) | The update is passive or stale data is acceptable | Serves stale data while revalidating |
| [`revalidateTag(tag, { expire: 0 })`](/docs/app/api-reference/functions/revalidateTag) | A webhook or external system requires immediate expiration | Waits for fresh data |
## Apply these patterns with SWR or TanStack Query
- [Client-side data fetching with SWR](/docs/app/guides/client-side-data-fetching/swr)
- [Client-side data fetching with TanStack Query](/docs/app/guides/client-side-data-fetching/tanstack-query)
See both patterns in the live [`next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev) and its [source code](https://github.com/vercel-labs/next-spa-patterns).
---
title: How to fetch client-side data with SWR
nav_title: SWR
description: Fetch client-side data with SWR, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [SWR](https://swr.vercel.app) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Fetch data on the client
SWR can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useSWR` when the component should render its own loading and error states. A conditional key delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isLoading,
} = useSWR(
query ? `/api/products?query=${encodeURIComponent(query)}` : null,
fetcher
)
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isLoading) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
## Use Suspense for client data
Use `suspense: true` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { Suspense } from 'react'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSWR(
`/api/products?query=${encodeURIComponent(query)}`,
fetcher,
{ suspense: true }
)
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
With an unconditional key, SWR defines `data` after Suspense resolves. Handle request errors with the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
The `isLoading` value is `true` when a request is running and there is no loaded data to display. The `isValidating` value is `true` whenever a request is running, including background revalidation.
With `suspense: true`, Suspense handles the initial no-data state. Later revalidation for the same key keeps the current data rendered instead of showing the Suspense fallback again. Use `isValidating` to provide background refresh feedback. Learn more about [SWR loading states](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux).
Learn more: [SWR data fetching](https://swr.vercel.app/docs/data-fetching).
> **Good to know:** Independent Suspense reads can start in parallel when they render in sibling components. Multiple Suspense reads in one component run sequentially. Learn more about [network waterfalls](/docs/app/guides/migrating/from-create-react-app#network-waterfalls) and [SWR Suspense](https://swr.vercel.app/docs/suspense).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and SWR should continue managing it in the browser. With SWR 2.3.0 and React 19, a Server Component can provide fallback data before the client takes over.
Scope `<SWRConfig>` to the route segment that owns the data. The provider keeps the `fallback` close to its consumer and avoids adding feature data to a shared layout:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
The fallback and Client Component must use the same SWR key. Define the key once so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
}
```
```js filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
}
```
In the page example, the Promise returned by `params.then()` keeps the fallback visible until the route parameters resolve. `ProductData` then creates a separate, unawaited `getProduct(id)` Promise for the SWR `fallback`. React passes that Promise through the React Server Component payload, and the component reading the matching key suspends until the data resolves.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }: { id: string }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
async function fetcher(url) {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly. If they drift, SWR ignores the fallback value and fetches on the client.
The `fallback` provides the hook's initial value. By default, SWR treats fallback data as stale and starts a browser revalidation after hydration.
SWR does not provide a time-based freshness window for fallback data. Setting `revalidateIfStale: false` skips revalidation when the hook mounts with cached data. This setting applies to every mount, unlike TanStack Query's `staleTime`.
Focus, reconnect, polling, and `mutate` can still revalidate the key. To refresh on a schedule, set [`refreshInterval`](https://swr.vercel.app/docs/revalidation#revalidate-on-interval).
The SWR key points to a [Route Handler](/docs/app/api-reference/file-conventions/route) with a `GET` method. The Route Handler can call the same `getProduct` function that provides the fallback, while the browser uses the URL for revalidation and polling.
Learn more: [SWR arguments and keys](https://swr.vercel.app/docs/arguments) and [SWR with Next.js App Router](https://swr.vercel.app/docs/with-nextjs).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data used as the SWR fallback. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id: string) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
SWR owns a separate browser cache, so its revalidation options do not need to match `cacheLife`.
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
+ tag: (id: string) => `product:${id}`,
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
+ tag: (id) => `product:${id}`,
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
## Coordinate server and client caches after mutations
The fallback provides the initial value. After hydration, SWR manages the browser cache and revalidation. For reused data, keep the SWR key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId) => `activity:${userId}`,
}
```
Use the same key for the fallback, the Client Component read, and the mutation. With SWR, pass the write to [`mutate`](https://swr.vercel.app/docs/mutation) and provide `optimisticData`. SWR shows the optimistic value immediately and rolls it back if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic SWR value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/swr). Learn more about [SWR mutation and optimistic updates](https://swr.vercel.app/docs/mutation) and the [SWR documentation](https://swr.vercel.app/docs/getting-started).
---
title: How to fetch client-side data with TanStack Query
nav_title: TanStack Query
description: Fetch client-side data with TanStack Query, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [TanStack Query](https://tanstack.com/query) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Set up the provider
Wrap the routes that use TanStack Query in a `QueryClientProvider`. Create a new query client for each server render and reuse one query client in the browser:
```tsx filename="app/products/providers.tsx"
'use client'
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
let browserQueryClient: QueryClient | undefined
function getQueryClient() {
// Keep server requests isolated and preserve the browser cache across renders.
if (typeof window === 'undefined') return new QueryClient()
browserQueryClient ??= new QueryClient()
return browserQueryClient
}
export function Providers({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={getQueryClient()}>
{children}
</QueryClientProvider>
)
}
```
Render the provider from the nearest shared layout:
```tsx filename="app/products/layout.tsx"
import { Providers } from './providers'
export default function Layout({ children }: LayoutProps<'/products'>) {
return <Providers>{children}</Providers>
}
```
See the [complete provider setup in the demo source](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query) or learn about provider options in the [TanStack Query Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Fetch data on the client
TanStack Query can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useQuery` when the component should render its own loading and error states. The `enabled` option delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useQuery } from '@tanstack/react-query'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isPending,
} = useQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
enabled: query.length > 0,
})
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isPending) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
Learn more: [TanStack Query queries](https://tanstack.com/query/latest/docs/framework/react/guides/queries).
## Use Suspense for client data
Use `useSuspenseQuery` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { Suspense } from 'react'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSuspenseQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
})
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
If the initial request fails, `useSuspenseQuery` propagates the error to the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
After a query has data, later refetches for the same query keep the cached data rendered instead of showing the Suspense fallback again. Use `isFetching` to provide background refresh feedback.
If the initial view needs the data, provide it from a Server Component as shown below.
> **Good to know:** Multiple `useSuspenseQuery` calls in one component run sequentially. Put independent queries in sibling components, or use [`useSuspenseQueries`](https://tanstack.com/query/latest/docs/framework/react/reference/useSuspenseQueries). Learn more about [request waterfalls](https://tanstack.com/query/latest/docs/framework/react/guides/request-waterfalls).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and TanStack Query should continue managing it in the browser. A Server Component can provide initial query data before the client takes over.
TanStack Query 5.40.0 or later can dehydrate pending queries. Start `prefetchQuery` without awaiting it, then pass the dehydrated state to `<HydrationBoundary>`. Override `queryFn` on the server because the Route Handler's relative URL only resolves in the browser:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
The server and Client Component must use the same query key. Keep the key and query options together so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
import { queryOptions } from '@tanstack/react-query'
export type Product = { id: string; name: string }
export const productCache = {
key: (id: string) => ['product', id] as const,
options: (id: string) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async (): Promise<Product> => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
staleTime: 30_000,
}),
}
```
```js filename="app/products/[id]/product-cache.js" switcher
import { queryOptions } from '@tanstack/react-query'
export const productCache = {
key: (id) => ['product', id],
options: (id) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async () => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
staleTime: 30_000,
}),
}
```
The query function fetches a [Route Handler](/docs/app/api-reference/file-conventions/route) so it can run on the client. The `staleTime` prevents an immediate client refetch by keeping the hydrated data fresh for 30 seconds. Choose a duration based on how quickly the data can change.
Larger features can place query options in a separate client-facing module as long as every caller imports the key from the same cache contract. Learn more about [TanStack Query defaults](https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults).
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProductData` prefetches below the boundary.
The Client Component reads the same query key with `useSuspenseQuery` (or `useQuery` to render `isPending` and `error` states inline):
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }: { id: string }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
Learn more: [TanStack Query Advanced SSR](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data provided to TanStack Query. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
import type { Product } from './product-cache'
export async function getProduct(id: string): Promise<Product> {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
TanStack Query owns a separate browser cache, so its `staleTime` does not need to match `cacheLife`.
With Cache Components enabled, Next.js also prerenders Client Components. Keep a query needed during the initial render behind [Suspense](/docs/app/getting-started/fetching-data#streaming). TanStack Query can read the current time while creating active query state, and the boundary lets Next.js defer that work instead of raising a [current-time prerender error](/docs/messages/blocking-prerender-current-time-client).
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => ['product', id] as const,
+ tag: (id: string) => `product:${id}`,
// ...
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => ['product', id],
+ tag: (id) => `product:${id}`,
// ...
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
> **Good to know:** TanStack Query's `dehydrate()` reads the current time during Cache Components prerendering. Use the [prerenderable hydration helper](#build-a-prerenderable-hydration-state) for cached initial data.
## Coordinate server and client caches after mutations
Hydration provides the initial client cache value. After hydration, TanStack Query owns the browser copy and its revalidation. For reused data, keep the query key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: ['activity', 'unread'] as const,
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: ['activity', 'unread'],
tag: (userId) => `activity:${userId}`,
}
```
On mutation, use `useMutation`'s [`onMutate`](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) callback to update the cache immediately and restore the previous value in `onError` if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic query value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors.
## Build a prerenderable hydration state
The TanStack Query pattern above uses `dehydrate()` to create the hydration state. With Cache Components, `dehydrate()` reads the current time (`Date.now()`) while prerendering and causes a [current-time prerender error](/docs/messages/blocking-prerender-current-time).
Instead, cache only that timestamp and build the dehydrated state by hand. Wrap the time read in [`use cache`](/docs/app/api-reference/directives/use-cache) with the same tags as the data reads. When a mutation invalidates those tags, the data and its timestamp advance together, so `<HydrationBoundary>` overwrites the client query on the next navigation:
```tsx filename="app/lib/hydrate.ts" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import {
defaultShouldDehydrateQuery,
QueryClient,
type DehydratedState,
type QueryKey,
} from '@tanstack/react-query'
type HydratedQuery = {
queryKey: QueryKey
data: unknown
}
type HydrationOptions = {
tags: string[]
}
async function getHydrationUpdatedAt(tags: string[]) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(
queries: HydratedQuery[],
options: HydrationOptions
): Promise<DehydratedState> {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
```js filename="app/lib/hydrate.js" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { defaultShouldDehydrateQuery, QueryClient } from '@tanstack/react-query'
async function getHydrationUpdatedAt(tags) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(queries, options) {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
Await the helper in the segment that owns the data, passing the data and the same tags used on the underlying `getProduct` read. Hand the result to `<HydrationBoundary>` inside `ProductData`:
```tsx filename="app/products/[id]/page.tsx" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }: { id: string }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
> **Good to know:** The timestamp must advance whenever the hydrated data changes. The helper suits tag-driven server data because both use the same tags. For time-driven server data, derive the data and hydration timestamp from the same cached snapshot instead of maintaining unrelated time windows.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query). Learn more about [TanStack Query optimistic updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) and the [TanStack Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
...@@ -59,6 +59,16 @@ app.prepare().then(() => { ...@@ -59,6 +59,16 @@ app.prepare().then(() => {
}) })
``` ```
> **Set your own response headers before calling `handle`**: Next.js begins sending the response inside `handle(req, res)`, so by the time its promise resolves `res.headersSent` is already `true` and any later `res.setHeader()` call is silently discarded. Set headers you own, such as `Set-Cookie`, before handing the request to Next.js:
>
> ```js
> res.setHeader('Set-Cookie', 'sessionId=abc123; Max-Age=2592000')
>
> await handle(req, res)
> ```
>
> The same ordering applies when wrapping Next.js in another framework, for example `reply.raw` in Fastify or `res` in Express.
> `server.js` does not run through the Next.js Compiler or bundling process. Make sure the syntax and source code this file requires are compatible with the current Node.js version you are using. [View an example](https://github.com/vercel/next.js/tree/canary/examples/custom-server). > `server.js` does not run through the Next.js Compiler or bundling process. Make sure the syntax and source code this file requires are compatible with the current Node.js version you are using. [View an example](https://github.com/vercel/next.js/tree/canary/examples/custom-server).
To run the custom server, you'll need to update the `scripts` in `package.json` like so: To run the custom server, you'll need to update the `scripts` in `package.json` like so:
......
...@@ -55,7 +55,7 @@ This approach works well when: ...@@ -55,7 +55,7 @@ This approach works well when:
### Data Access Layer ### Data Access Layer
For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is a internal library that controls how and when data is fetched, and what gets passed to your render context. For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is an internal library that controls how and when data is fetched, and what gets passed to your render context.
A Data Access Layer should: A Data Access Layer should:
......
...@@ -76,7 +76,7 @@ Now go to the Debug panel (`Ctrl+Shift+D` on Windows/Linux, `⇧+⌘+D` on macOS ...@@ -76,7 +76,7 @@ Now go to the Debug panel (`Ctrl+Shift+D` on Windows/Linux, `⇧+⌘+D` on macOS
## Using the Debugger in Jetbrains WebStorm ## Using the Debugger in Jetbrains WebStorm
Click the drop down menu listing the runtime configuration, and click `Edit Configurations...`. Create a `JavaScript Debug` debug configuration with `http://localhost:3000` as the URL. Customize to your liking (e.g. Browser for debugging, store as project file), and click `OK`. Run this debug configuration, and the selected browser should automatically open. At this point, you should have 2 applications in debug mode: the NextJS node application, and the client/browser application. Click the drop down menu listing the runtime configuration, and click `Edit Configurations...`. Create a `JavaScript Debug` debug configuration with `http://localhost:3000` as the URL. Customize to your liking (e.g. Browser for debugging, store as project file), and click `OK`. Run this debug configuration, and the selected browser should automatically open. At this point, you should have 2 applications in debug mode: the Next.js node application, and the client/browser application.
## Debugging with Browser DevTools ## Debugging with Browser DevTools
......
...@@ -163,7 +163,7 @@ NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk ...@@ -163,7 +163,7 @@ NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
This will tell Next.js to replace all references to `process.env.NEXT_PUBLIC_ANALYTICS_ID` in the Node.js environment with the value from the environment in which you run `next build`, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser. This will tell Next.js to replace all references to `process.env.NEXT_PUBLIC_ANALYTICS_ID` in the Node.js environment with the value from the environment in which you run `next build`, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser.
> **Note**: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all `NEXT_PUBLIC_` variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to setup your own API to provide them to the client (either on demand or during initialization). > **Note**: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all `NEXT_PUBLIC_` variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to set up your own API to provide them to the client (either on demand or during initialization).
```js filename="pages/index.js" ```js filename="pages/index.js"
import setupAnalyticsService from '../lib/my-analytics-service' import setupAnalyticsService from '../lib/my-analytics-service'
......
...@@ -131,7 +131,7 @@ export async function updateUser(userId, formData) {} ...@@ -131,7 +131,7 @@ export async function updateUser(userId, formData) {}
Forms can be validated on the client or server. Forms can be validated on the client or server.
- For **client-side validation**, you can use the HTML attributes like `required` and `type="email"` for basic validation. - For **client-side validation**, you can use the HTML attributes like `required` and `type="email"` for basic validation.
- For **server-side validation**, you can use a library like [zod](https://zod.dev/) to validate the form fields. For example: - For **server-side validation**, you can use a schema validation library like [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/) to validate the form fields. For example:
```tsx filename="app/actions.ts" switcher ```tsx filename="app/actions.ts" switcher
'use server' 'use server'
......
...@@ -7,7 +7,7 @@ related: ...@@ -7,7 +7,7 @@ related:
description: Explore the full instant API, caching, and revalidation. description: Explore the full instant API, caching, and revalidation.
links: links:
- app/api-reference/file-conventions/route-segment-config/instant - app/api-reference/file-conventions/route-segment-config/instant
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
- app/getting-started/caching - app/getting-started/caching
- app/getting-started/revalidating - app/getting-started/revalidating
- app/guides/prefetching - app/guides/prefetching
...@@ -36,7 +36,41 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe ...@@ -36,7 +36,41 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe
</details> </details>
Runtime prefetching extends the static shell with a link's URL data (`searchParams` and `params`) by invoking the route at prefetch time. Ensuring navigations are instant is the foundation: a route that doesn't navigate instantly without runtime prefetching won't navigate instantly with it either. See [Runtime prefetching](/docs/app/guides/runtime-prefetching) for the patterns. With `prefetch={true}`, per-link prefetching resolves a link's URL data (`searchParams` and `params`) before navigation. First make the route instant with its App Shell. Per-link prefetching cannot fix a route that blocks without it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) for the patterns.
## Quick start
Getting the most out of Instant Navigation requires enabling [Cache Components](/docs/app/guides/migrating-to-cache-components) and [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), then following the [validation errors](#validate-instant-navigation) that appear:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
```
To help you automate this process with an agent, there's a Skill for each part, [next-cache-components-adoption](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) and [next-partial-prefetching-adoption](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption). If you'd like to enable everything, give your agent this prompt:
```prompt
Adopt Cache Components and Partial Prefetching in this app so its navigations become instant. There is a Skill for each migration.
1. Before you change anything, explain to me in plain terms what Instant Navigation is and what adopting it will change.
2. Install the Skills you need, then verify your changes against a running dev server with next-dev-loop and agent-browser as you go:
- next-cache-components-adoption: https://www.skills.sh/vercel/next.js/next-cache-components-adoption
- next-partial-prefetching-adoption: https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption
- next-dev-loop: https://www.skills.sh/vercel/next.js/next-dev-loop
3. Each Skill leaves decisions to me, like how much of the work lands in each pull request. Put those questions to me and wait for my answers instead of deciding on my behalf. Adopt Cache Components first, then Partial Prefetching, following the workflow each Skill lays out. Don't rush to a passing build.
4. When you finish a step, show me a table of the routes you touched and what changed on each, and talk me through what it means for the app. Keep it to the outcome, not the implementation details.
```
The rest of this guide covers the tools these migrations use, walks a navigation that blocks to instant, inspects what lands in the initial UI, and locks the result in with end-to-end tests.
## The tools ## The tools
...@@ -44,17 +78,17 @@ Runtime prefetching extends the static shell with a link's URL data (`searchPara ...@@ -44,17 +78,17 @@ Runtime prefetching extends the static shell with a link's URL data (`searchPara
With Cache Components, **caching directives** (`"use cache"` and its variants) assign a lifetime to an async function's result, which is what lets Next.js include it in the static shell. With Cache Components, **caching directives** (`"use cache"` and its variants) assign a lifetime to an async function's result, which is what lets Next.js include it in the static shell.
> **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/runtime-prefetching#use-cache-private) in the runtime prefetching guide for how it pairs with prefetching. > **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/optimizing-prefetching#use-cache-private) in the Optimizing prefetching guide for how it pairs with prefetching.
**`<Suspense>`** declares fallback UI for parts of the tree that read uncached data or runtime APIs like `cookies()` and `headers()`; the content streams into the fallback when it resolves. **`<Suspense>`** declares fallback UI for parts of the tree that read uncached data or runtime APIs like `cookies()` and `headers()`; the content streams into the fallback when it resolves.
> **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. With [runtime prefetching](/docs/app/guides/runtime-prefetching), the information is available and such a fallback becomes part of the instant UI. Cached values like timestamps or data fetches can sit directly inside the fallback. > **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. For a link with `prefetch={true}`, [per-link prefetching](/docs/app/guides/optimizing-prefetching) makes URL data available before navigation, so the fallback can become part of the prefetched UI. Cached values like timestamps or data fetches can sit directly inside the fallback.
Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. [Runtime prefetching](/docs/app/guides/runtime-prefetching) builds on it, resolving a link's URL data on top. Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route, which renders during client navigations while remaining content streams. Partial Prefetching uses the App Shell as the default `<Link>` prefetch. A link with `prefetch={true}` can also resolve cached content that depends on that link's URL data.
### Tune what `<Link>` prefetches ### Prefetch URL data for a link
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. The shell is shared across every link to the same route, so rendering a `<Link>` is effectively free. Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. Links to the same route share one App Shell instead of triggering a separate App Shell request for each link.
To prefetch the page content alongside the shell for a specific link, set [`prefetch={true}`](/docs/app/api-reference/components/link#prefetch): To prefetch the page content alongside the shell for a specific link, set [`prefetch={true}`](/docs/app/api-reference/components/link#prefetch):
...@@ -64,7 +98,7 @@ To prefetch the page content alongside the shell for a specific link, set [`pref ...@@ -64,7 +98,7 @@ To prefetch the page content alongside the shell for a specific link, set [`pref
</Link> </Link>
``` ```
With Partial Prefetching enabled, `prefetch={true}` also opts the link into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click. With Partial Prefetching enabled, `prefetch={true}` also opts the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click.
### Validate instant navigation ### Validate instant navigation
...@@ -298,7 +332,7 @@ bun add -D @next/playwright @playwright/test ...@@ -298,7 +332,7 @@ bun add -D @next/playwright @playwright/test
A route can be reached two ways, and a `<Suspense>` boundary can cover one without covering the other: A route can be reached two ways, and a `<Suspense>` boundary can cover one without covering the other:
- **Initial page load**: Use `page.goto()` to test the static UI from the document response. - **Initial page load**: Use `page.goto()` to test the static UI from the document response.
- **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Runtime prefetching](/docs/app/guides/runtime-prefetching) can add request-specific content to this UI. - **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) can add request-specific content to this UI.
```typescript filename="e2e/navigation.test.ts" highlight={6-14,20-25} ```typescript filename="e2e/navigation.test.ts" highlight={6-14,20-25}
import { test, expect } from '@playwright/test' import { test, expect } from '@playwright/test'
...@@ -490,7 +524,7 @@ Use the [DevTools](#visualize-loading-states-with-the-nextjs-devtools) to see wh ...@@ -490,7 +524,7 @@ Use the [DevTools](#visualize-loading-states-with-the-nextjs-devtools) to see wh
## AI workflow ## AI workflow
An AI coding agent can run this workflow to make a navigation instant: At a high level, an agent optimizes a single navigation like this:
- **Observe**: read validation insights and choose the exact navigation and UI that should appear immediately. - **Observe**: read validation insights and choose the exact navigation and UI that should appear immediately.
- **Test**: confirm the target UI renders normally, then write an `instant()` test and verify that it fails before changing the route. - **Test**: confirm the target UI renders normally, then write an `instant()` test and verify that it fails before changing the route.
...@@ -505,7 +539,7 @@ Agents working on a Cache Components route typically reach for three levers: ...@@ -505,7 +539,7 @@ Agents working on a Cache Components route typically reach for three levers:
- **Push down**: extract I/O into a Suspense-wrapped child so the parent stays static and static siblings lift into the shell. - **Push down**: extract I/O into a Suspense-wrapped child so the parent stays static and static siblings lift into the shell.
- **Cache**: pair `'use cache'` with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) to assign a freshness profile. - **Cache**: pair `'use cache'` with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) to assign a freshness profile.
- **Runtime prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [runtime prefetching](/docs/app/guides/runtime-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it. - **Per-link prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [per-link prefetching](/docs/app/guides/optimizing-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it.
Each refactor should pair with a before/after capture to verify the change actually landed. Identical-looking captures mean the refactor didn't take effect. Each refactor should pair with a before/after capture to verify the change actually landed. Identical-looking captures mean the refactor didn't take effect.
...@@ -545,6 +579,6 @@ For opted-out segments, the navigation blocks on the server. If the content depe ...@@ -545,6 +579,6 @@ For opted-out segments, the navigation blocks on the server. If the content depe
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and the migration path off `unstable_eager` - [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and the migration path off `unstable_eager`
- [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration - [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration
- [Runtime prefetching](/docs/app/guides/runtime-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and you want it in the shell - [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and should resolve before navigation
- [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering
- [Revalidating](/docs/app/getting-started/revalidating) for how to expire cached data with `cacheLife` and `updateTag` - [Revalidating](/docs/app/getting-started/revalidating) for how to expire cached data with `cacheLife` and `updateTag`
...@@ -18,7 +18,7 @@ To set up instrumentation, create `instrumentation.ts|js` file in the **root dir ...@@ -18,7 +18,7 @@ To set up instrumentation, create `instrumentation.ts|js` file in the **root dir
Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated, and must complete before the server is ready to handle requests. Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated, and must complete before the server is ready to handle requests.
For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/observability/otel-overview): For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/tracing/instrumentation):
```ts filename="instrumentation.ts" switcher ```ts filename="instrumentation.ts" switcher
import { registerOTel } from '@vercel/otel' import { registerOTel } from '@vercel/otel'
......
...@@ -434,6 +434,7 @@ Add `useOptimistic` with a reducer to remap the card's status on the current fra ...@@ -434,6 +434,7 @@ Add `useOptimistic` with a reducer to remap the card's status on the current fra
'use client' 'use client'
import { startTransition, use, useOptimistic } from 'react' import { startTransition, use, useOptimistic } from 'react'
import { toast } from 'sonner'
import { updateStatus } from '@/features/task/task-actions' import { updateStatus } from '@/features/task/task-actions'
export function Board({ tasksPromise }) { export function Board({ tasksPromise }) {
...@@ -449,7 +450,8 @@ export function Board({ tasksPromise }) { ...@@ -449,7 +450,8 @@ export function Board({ tasksPromise }) {
function handleDrop(targetStatus, taskId) { function handleDrop(targetStatus, taskId) {
startTransition(async () => { startTransition(async () => {
moveTask({ taskId, status: targetStatus }) moveTask({ taskId, status: targetStatus })
await updateStatus(taskId, targetStatus) const result = await updateStatus(taskId, targetStatus)
if (!result.success) toast.error(result.error)
}) })
} }
...@@ -467,9 +469,9 @@ export function Board({ tasksPromise }) { ...@@ -467,9 +469,9 @@ export function Board({ tasksPromise }) {
} }
``` ```
The reducer maps over the task list and updates the status of the dragged card, leaving the rest unchanged. If a background refresh arrives mid-drag, for example from polling or another user's mutation, React re-runs the reducer with the updated base data so the optimistic move sits on top of fresh data. The reducer maps over the task list and updates the status of the dragged card, leaving the rest unchanged. If a background refresh arrives mid-drag, for example from polling or another user's mutation, React re-runs the reducer with the updated base data so the optimistic move sits on top of fresh data. The Server Function returns an error result when the task no longer exists, which the client displays in a toast.
This step uses the standalone `startTransition` instead of `useTransition` because the hook's `isPending` would trigger the board fade from Step 3. The optimistic move already covers the visual feedback, so no pending indicator is needed. If the Server Function fails, the card reverts. This step uses the standalone `startTransition` instead of `useTransition` because the hook's `isPending` would trigger the board fade from Step 3. The optimistic move already covers the visual feedback, so no pending indicator is needed. If the Server Function returns an expected error, the card reverts. Unexpected errors are forwarded to the nearest [error boundary](/docs/app/getting-started/error-handling).
A card dragged from "Todo" to "In Progress" now lands in the target column the moment you release. A card dragged from "Todo" to "In Progress" now lands in the target column the moment you release.
...@@ -724,11 +726,17 @@ The per-id tag `task-${id}` gives a single task its own handle. The broader `tas ...@@ -724,11 +726,17 @@ The per-id tag `task-${id}` gives a single task its own handle. The broader `tas
'use server' 'use server'
import { updateTag } from 'next/cache' import { updateTag } from 'next/cache'
import { updateTaskStatus } from '@/lib/db'
export async function updateStatus(taskId: string, newStatus: Status) { export async function updateStatus(taskId: string, newStatus: Status) {
// …mutate const updated = await updateTaskStatus(taskId, newStatus)
if (!updated) {
return { success: false as const, error: 'Task no longer exists' }
}
updateTag('tasks') updateTag('tasks')
updateTag(`task-${taskId}`) updateTag(`task-${taskId}`)
return { success: true as const, status: newStatus }
} }
``` ```
...@@ -738,7 +746,7 @@ In this demo, the comment thread stays dynamic because readers expect the curren ...@@ -738,7 +746,7 @@ In this demo, the comment thread stays dynamic because readers expect the curren
#### Prefetch the destination with the real request #### Prefetch the destination with the real request
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [runtime prefetching](/docs/app/guides/runtime-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click: Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click:
```tsx filename="features/task/components/task-card.tsx" ```tsx filename="features/task/components/task-card.tsx"
<Link href={`/task/${id}`} prefetch={true}> <Link href={`/task/${id}`} prefetch={true}>
...@@ -746,7 +754,7 @@ Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next ...@@ -746,7 +754,7 @@ Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next
</Link> </Link>
``` ```
Runtime prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks. Per-link prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks.
## Next steps ## Next steps
...@@ -760,12 +768,14 @@ The patterns in this guide combine a handful of primitives: ...@@ -760,12 +768,14 @@ The patterns in this guide combine a handful of primitives:
| A form needs pending, reset, and result state | [`useActionState`](https://react.dev/reference/react/useActionState) | | A form needs pending, reset, and result state | [`useActionState`](https://react.dev/reference/react/useActionState) |
| An ancestor should show pending state for work happening elsewhere | [`data-pending`](https://react.dev/reference/react-dom/components/form#props) attribute styled with CSS | | An ancestor should show pending state for work happening elsewhere | [`data-pending`](https://react.dev/reference/react-dom/components/form#props) attribute styled with CSS |
| Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) | | Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) |
| Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [Runtime prefetching](/docs/app/guides/runtime-prefetching) via `prefetch={true}` for content that depends on URL data | | Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [per-link prefetching](/docs/app/guides/optimizing-prefetching) via `prefetch={true}` for content that depends on URL data |
Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving. Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving.
Related guides: Related guides:
- [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and client cache coordination
- [Streaming](/docs/app/guides/streaming) for loading boundaries and `<Suspense>` patterns - [Streaming](/docs/app/guides/streaming) for loading boundaries and `<Suspense>` patterns
- [Instant Navigation](/docs/app/guides/instant-navigation) for validating that navigations stay instant - [Instant Navigation](/docs/app/guides/instant-navigation) for validating that navigations stay instant
- [View Transitions](/docs/app/guides/view-transitions) for animating state changes - [View Transitions](/docs/app/guides/view-transitions) for animating state changes
- [Single-page applications](/docs/app/guides/single-page-applications#mutating-data-with-server-actions) for a shared-reducer `useOptimistic` example that keeps client and server list updates in sync
...@@ -74,7 +74,7 @@ This allows `.mdx` files to act as pages, routes, or imports in your application ...@@ -74,7 +74,7 @@ This allows `.mdx` files to act as pages, routes, or imports in your application
### Handling `.md` files ### Handling `.md` files
By default, `next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option: By default, `@next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option:
```js filename="next.config.mjs" ```js filename="next.config.mjs"
const withMDX = createMDX({ const withMDX = createMDX({
......
...@@ -10,6 +10,7 @@ related: ...@@ -10,6 +10,7 @@ related:
- app/getting-started/caching - app/getting-started/caching
- app/guides/preserving-ui-state - app/guides/preserving-ui-state
- app/guides/incremental-static-regeneration-cache-components - app/guides/incremental-static-regeneration-cache-components
- app/guides/authentication-with-cache-components
- app/api-reference/functions/generate-static-params - app/api-reference/functions/generate-static-params
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
--- ---
...@@ -95,6 +96,8 @@ You don't have to migrate every route at once. `instant = false` lets you get th ...@@ -95,6 +96,8 @@ You don't have to migrate every route at once. `instant = false` lets you get th
npx @next/codemod@canary cache-components-instant-false ./app npx @next/codemod@canary cache-components-instant-false ./app
``` ```
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
The app keeps building and serving, now with validation deferred for the opted-out routes. The app keeps building and serving, now with validation deferred for the opted-out routes.
3. **Fix synchronous IO. It can't be deferred.** Calls like `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` during prerender throw a build error that `instant = false` does not clear, so a route that uses them won't build until you address it, opt-out or not. Move the call out of the prerendered shell so it runs at request time: wrap the part that needs it in [`<Suspense>`](https://react.dev/reference/react/Suspense) and call [`connection()`](/docs/app/api-reference/functions/connection) before the call, or move it into a Client Component. 3. **Fix synchronous IO. It can't be deferred.** Calls like `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` during prerender throw a build error that `instant = false` does not clear, so a route that uses them won't build until you address it, opt-out or not. Move the call out of the prerendered shell so it runs at request time: wrap the part that needs it in [`<Suspense>`](https://react.dev/reference/react/Suspense) and call [`connection()`](/docs/app/api-reference/functions/connection) before the call, or move it into a Client Component.
...@@ -552,11 +555,11 @@ export default async function Page() { ...@@ -552,11 +555,11 @@ export default async function Page() {
## `generateStaticParams` and `dynamicParams` ## `generateStaticParams` and `dynamicParams`
Two behaviors change for [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) when Cache Components is enabled. Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) handle params.
### `generateStaticParams` must return at least one param ### `generateStaticParams` must return at least one param
**Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [App Shell](/docs/app/glossary#app-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params). **Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [static shell](/docs/app/glossary#static-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params).
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
// Before - defer all paths to runtime // Before - defer all paths to runtime
...@@ -588,13 +591,19 @@ export async function generateStaticParams() { ...@@ -588,13 +591,19 @@ export async function generateStaticParams() {
} }
``` ```
Paths you don't return are still served. Next.js serves the App Shell instantly, then upgrades it in the background once the params are known. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow. Paths you don't return are still served. Next.js prerenders a static shell for the unknown params and streams the rest at request time. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow.
### `dynamicParams` is not supported
**Delete the export.** With Cache Components enabled, exporting `dynamicParams` fails the build with this error message:
> Route segment config "dynamicParams" is not compatible with `nextConfig.cacheComponents`.
### `dynamicParams` no longer blocks the first visit Params not returned by `generateStaticParams` are rendered on request. If you used `dynamicParams: false` to reject them, call [`notFound()`](/docs/app/api-reference/functions/not-found) in the page when the param doesn't resolve to real data.
**`dynamicParams: true` (the default) now serves an App Shell instead of blocking.** Previously, visiting a param not returned by `generateStaticParams` blocked the response while the page rendered. With Cache Components, Next.js serves the App Shell instantly, then upgrades it in the background with the now-known params. `dynamicParams: false` is unchanged: unspecified paths still 404. ### Await `params` inside `<Suspense>`
To produce the App Shell, pass the `params` promise into a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary instead of awaiting it at the top of the component, so unknown params can still prerender. To produce the static shell, pass the `params` promise into a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary instead of awaiting it at the top of the component, so unknown params can still prerender.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
// Before - awaiting params at the top blocks the shell // Before - awaiting params at the top blocks the shell
...@@ -652,7 +661,7 @@ async function Post({ params }) { ...@@ -652,7 +661,7 @@ async function Post({ params }) {
} }
``` ```
The same applies to client hooks that read the route. When the route's pathname is fully known, they resolve during prerendering and need no boundary. When it depends on dynamic params not yet known, they suspend, wherever the component sits. A nav or breadcrumb in a shared layout, for instance, suspends while Next.js generates the App Shell for any route below it that has dynamic params. Wrap the component that reads the hook in `<Suspense>` (push the read down to the smallest leaf so the rest stays prerendered), or the build fails: The same applies to client hooks that read the route. When the route's pathname is fully known, they resolve during prerendering and need no boundary. When it depends on dynamic params not yet known, they suspend, wherever the component sits. A nav or breadcrumb in a shared layout, for instance, suspends while Next.js generates the static shell for any route below it that has dynamic params. Wrap the component that reads the hook in `<Suspense>` (push the read down to the smallest leaf so the rest stays prerendered), or the build fails:
- [`usePathname`](/docs/app/api-reference/functions/use-pathname) - [`usePathname`](/docs/app/api-reference/functions/use-pathname)
- [`useParams`](/docs/app/api-reference/functions/use-params) - [`useParams`](/docs/app/api-reference/functions/use-params)
......
...@@ -108,7 +108,7 @@ To upgrade your links to Next.js 13, you can use the [`new-link` codemod](/docs/ ...@@ -108,7 +108,7 @@ To upgrade your links to Next.js 13, you can use the [`new-link` codemod](/docs/
The behavior of [`next/script`](/docs/app/api-reference/components/script) has been updated to support both `pages` and `app`, but some changes need to be made to ensure a smooth migration: The behavior of [`next/script`](/docs/app/api-reference/components/script) has been updated to support both `pages` and `app`, but some changes need to be made to ensure a smooth migration:
- Move any `beforeInteractive` scripts you previously included in `_document.js` to the root layout file (`app/layout.tsx`). - Move any `beforeInteractive` scripts you previously included in `_document.js` to a [root layout](/docs/app/api-reference/file-conventions/layout#root-layout), such as `app/layout.tsx` or `app/[locale]/layout.tsx`.
- The experimental `worker` strategy does not yet work in `app` and scripts denoted with this strategy will either have to be removed or modified to use a different strategy (e.g. `lazyOnload`). - The experimental `worker` strategy does not yet work in `app` and scripts denoted with this strategy will either have to be removed or modified to use a different strategy (e.g. `lazyOnload`).
- `onLoad`, `onReady`, and `onError` handlers will not work in Server Components so make sure to move them to a [Client Component](/docs/app/getting-started/server-and-client-components) or remove them altogether. - `onLoad`, `onReady`, and `onError` handlers will not work in Server Components so make sure to move them to a [Client Component](/docs/app/getting-started/server-and-client-components) or remove them altogether.
......
...@@ -355,7 +355,7 @@ This tells Next.js to generate a single route for the empty slug (`/`), effectiv ...@@ -355,7 +355,7 @@ This tells Next.js to generate a single route for the empty slug (`/`), effectiv
### Step 7: Add a Client-Only Entrypoint ### Step 7: Add a Client-Only Entrypoint
Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that clients components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript. Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that Client Components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript.
Create a `client.tsx` (or `client.js`) in `app/[[...slug]]/`: Create a `client.tsx` (or `client.js`) in `app/[[...slug]]/`:
......
...@@ -307,7 +307,7 @@ For most apps, the pending loading state is enough. Add a banner in the root lay ...@@ -307,7 +307,7 @@ For most apps, the pending loading state is enough. Add a banner in the root lay
The same pattern extends to parameterized routes. A route like `/chats/[id]` renders its shared [App Shell](/docs/app/glossary#app-shell) when you navigate to `/chats/42` offline, and the dynamic messages behind its `<Suspense>` boundary load when the connection returns. The same pattern extends to parameterized routes. A route like `/chats/[id]` renders its shared [App Shell](/docs/app/glossary#app-shell) when you navigate to `/chats/42` offline, and the dynamic messages behind its `<Suspense>` boundary load when the connection returns.
If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [runtime prefetching](/docs/app/guides/runtime-prefetching) to learn more. If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to learn more.
## Retry Server Actions after the network returns ## Retry Server Actions after the network returns
......
...@@ -195,7 +195,7 @@ It will work both on Vercel and when self-hosted. ...@@ -195,7 +195,7 @@ It will work both on Vercel and when self-hosted.
We made sure that OpenTelemetry works out of the box on Vercel. We made sure that OpenTelemetry works out of the box on Vercel.
Follow [Vercel documentation](https://vercel.com/docs/concepts/observability/otel-overview/quickstart) to connect your project to an observability provider. Follow [Vercel documentation](https://vercel.com/docs/tracing/instrumentation) to connect your project to an observability provider.
#### Self-hosting #### Self-hosting
......
--- ---
title: Runtime prefetching title: Optimizing prefetching
description: Prefetch URL data alongside the App Shell using the prefetch segment config and per-session caching directives. description: Resolve per-link URL data with the prefetch prop, or include session data in the App Shell.
nav_title: Runtime prefetching nav_title: Optimizing prefetching
version: experimental
related: related:
title: Learn more title: Learn more
description: Validate your structure and review the caching primitives. description: Validate your structure and review the caching primitives.
...@@ -16,15 +15,11 @@ related: ...@@ -16,15 +15,11 @@ related:
- app/guides/prefetching - app/guides/prefetching
--- ---
Prefetching downloads a route's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip. Prefetching downloads a route's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip. The [Prefetching guide](/docs/app/guides/prefetching) covers what the App Router prefetches by default.
The regular App Router prefetches a route all or nothing: the full route when it's static, and nothing for a dynamic route without a [`loading.js`](/docs/app/api-reference/file-conventions/loading). With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), a [`<Link>`](/docs/app/api-reference/components/link) prefetches one reusable [**App Shell**](/docs/app/glossary#app-shell) per route by default. The App Shell includes the route's static output. For routes that read [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), it also includes session-specific UI. Links to the same route reuse that App Shell.
[Cache Components](/docs/app/getting-started/caching) with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled takes a different approach, prefetching one reusable [**App Shell**](/docs/app/glossary#app-shell) per route rather than a separate prefetch per link. The shell contains the route's static output, and for a route that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) (session data), it also carries UI gated behind that session data. The shared App Shell does not include URL data that varies by destination, such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional). Set `prefetch={true}` on a link to resolve cached content that depends on its [URL data](/docs/app/glossary#url-data) before navigation instead of streaming that content after navigation.
Any number of links to the same route share that one shell, fetched once as a [`<Link>`](/docs/app/api-reference/components/link) enters the viewport and reused for the rest.
The shell cannot carry data that varies per link: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional), the route's [URL data](/docs/app/glossary#url-data). **Runtime prefetching** resolves that URL data at prefetch time, ready before the click rather than streaming in after it.
This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled: This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled:
...@@ -41,9 +36,9 @@ export default nextConfig ...@@ -41,9 +36,9 @@ export default nextConfig
It also assumes your route is already structured for instant navigation. If it isn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first. It also assumes your route is already structured for instant navigation. If it isn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first.
## What runtime prefetching does ## Resolve URL data at prefetch time
Runtime prefetching is opted into per link with `<Link prefetch={true}>`. Any destination with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled supports it, either globally via `partialPrefetching` or per segment with [`prefetch = 'partial'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#partial). Set `<Link prefetch={true}>` to resolve URL data for that link before navigation. The destination must use [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), enabled globally with `partialPrefetching` or per segment with [`prefetch = 'partial'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#partial).
A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`: A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`:
...@@ -97,21 +92,19 @@ async function search(q: string) { ...@@ -97,21 +92,19 @@ async function search(q: string) {
Without `prefetch={true}`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in. Without `prefetch={true}`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in.
With `prefetch={true}` on the link, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link's URL, known at prefetch time, and the cached `search(q)` fills in from there. On the click, the results render immediately, with no fallback. With `prefetch={true}` on the link, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link's URL, known at prefetch time, and the cached `search(q)` provides the result. On the click, the results render immediately, with no fallback.
The prerender advances through anything static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation). The prerender advances through anything static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation).
More of the page is rendered before the user clicks, with fewer loading states. Generating the per-link prefetch costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is generated per prefetch.
Generating it costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is prefetched at runtime.
> **Good to know:** A cold cache (first visit, or after expiration) means the server still has to compute the cached result. Users may see a loading spinner on that first navigation. Subsequent navigations are instant as long as the cache is warm. > **Good to know:** A cold cache (first visit, or after expiration) means the server still has to compute the cached result. Users may see a loading spinner on that first navigation. Subsequent navigations are instant as long as the cache is warm.
Like `searchParams`, `params` needs a `<Suspense>` boundary, even when the values are predefined by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). A statically known param still belongs to one URL. Runtime prefetching resolves the values `generateStaticParams` does not cover. Like `searchParams`, `params` needs a `<Suspense>` boundary, even when the values are predefined by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). A statically known param still belongs to one URL. A per-link prefetch with `prefetch={true}` resolves the values `generateStaticParams` does not cover.
## Session data resolves in the shell ## Include session data in the shell
Runtime prefetching is for URL data. Session data is handled separately. A route that reads `cookies()` or `headers()`, including through `"use cache: private"`, gets an App Shell that includes its session data, cached per session on the client and ready on navigation without a per-link runtime prefetch. `prefetch={true}` resolves URL data. Session data is handled separately. A route that reads `cookies()` or `headers()`, including through `"use cache: private"`, gets an App Shell that includes its session data, cached per session on the client and ready on navigation without a per-link prefetch.
A lookup based on session data needs a cache lifetime, the same way `search(q)` did for the URL. Take a dashboard nav that reads a cookie, then looks up content based on it: A lookup based on session data needs a cache lifetime, the same way `search(q)` did for the URL. Take a dashboard nav that reads a cookie, then looks up content based on it:
...@@ -191,9 +184,11 @@ Here `cookies()` lives inside the cached function, which only works under `"use ...@@ -191,9 +184,11 @@ Here `cookies()` lives inside the cached function, which only works under `"use
Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible. Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible.
## Per-link prefetching trade-offs {/* TODO(optimizing-prefetching): add an "Exclude content until navigation" section once `await navigation()` (ships as `unstable_navigation`, vercel/next.js#96069) merges. This is the second direction, gating content OUT of the prefetch rather than resolving URL data into it: the prefetch stops at `await navigation()` (code after it does not run at prefetch time), and on the actual navigation (or build/ISR) it runs and streams in. Unlike `await connection()`, content below the gate stays cacheable. It can't be called inside `use cache` / `use cache: private` yet, so the pattern is `await navigation()` in an uncached wrapper with the cache directive on an inner function below the gate. Do NOT publish until merged; validate empirically against the PR branch first. */}
## Trade-offs
Use it on routes where: Use `prefetch={true}` on routes where:
- Part of the component tree depends on URL data: the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) - Part of the component tree depends on URL data: the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params)
- That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`) - That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
...@@ -205,16 +200,16 @@ Skip it when the prefetch can't produce a better UI than the App Shell. Each vis ...@@ -205,16 +200,16 @@ Skip it when the prefetch can't produce a better UI than the App Shell. Each vis
- The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way. - The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way.
- The route is rarely navigated to. You pay per visible link, regardless of click-through. - The route is rarely navigated to. You pay per visible link, regardless of click-through.
A per-link runtime prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell. That shell is the reliable baseline, and runtime prefetching only layers on top when it arrives in time. A per-link prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell.
When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) prefetches only the App Shell, so it doesn't carry this cost. When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) prefetches only the App Shell, so it doesn't carry this cost.
| | App Shell | Per-link runtime prefetch with `prefetch={true}` | | | App Shell | Per-link prefetch with `prefetch={true}` |
| ------- | ------------------------------------------- | ------------------------------------------------ | | ------- | ------------------------------------------- | ---------------------------------------- |
| Scope | One per route | One per visible `<Link prefetch={true}>` | | Scope | One per route | One per visible `<Link prefetch={true}>` |
| Content | Route's rendered output minus per-link data | Same, plus per-link URL data resolved | | Content | Route's rendered output minus per-link data | Same, plus per-link URL data resolved |
| Cost | Bounded by route count | Bounded by visible-link count | | Cost | Bounded by route count | Bounded by visible-link count |
| Role | Every route's instant floor | Upgrade: more rendered before click | | Role | Default prefetch | More rendered before click |
## Next steps ## Next steps
......
...@@ -85,10 +85,10 @@ Next.js stores prefetched React Server Component payloads in memory, keyed by ro ...@@ -85,10 +85,10 @@ Next.js stores prefetched React Server Component payloads in memory, keyed by ro
With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled via the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) config (which requires [Cache Components](/docs/app/getting-started/caching)), prefetching switches from the all-or-nothing model above to a per-route [App Shell](/docs/app/glossary#app-shell): With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled via the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) config (which requires [Cache Components](/docs/app/getting-started/caching)), prefetching switches from the all-or-nothing model above to a per-route [App Shell](/docs/app/glossary#app-shell):
- **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full. - **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full.
- **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/runtime-prefetching). - **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/optimizing-prefetching).
- **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches. - **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches.
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to resolve cached URL-specific content before navigation with `prefetch={true}`.
## Controlling prefetching ## Controlling prefetching
......
...@@ -376,11 +376,11 @@ Consider the following data structure: ...@@ -376,11 +376,11 @@ Consider the following data structure:
} }
``` ```
In [Proxy](/docs/app/api-reference/file-conventions/proxy), you can read from a database such as Vercel's [Edge Config](https://vercel.com/docs/edge-config/get-started) or [Redis](https://vercel.com/docs/redis), and redirect the user based on the incoming request: In [Proxy](/docs/app/api-reference/file-conventions/proxy), you can read from a database such as Vercel's [Global Config](https://vercel.com/docs/global-config/get-started) or [Redis](https://vercel.com/docs/redis), and redirect the user based on the incoming request:
```ts filename="proxy.ts" switcher ```ts filename="proxy.ts" switcher
import { NextResponse, NextRequest } from 'next/server' import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config' import { get } from '@vercel/global-config'
type RedirectEntry = { type RedirectEntry = {
destination: string destination: string
...@@ -404,7 +404,7 @@ export async function proxy(request: NextRequest) { ...@@ -404,7 +404,7 @@ export async function proxy(request: NextRequest) {
```js filename="proxy.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { get } from '@vercel/edge-config' import { get } from '@vercel/global-config'
export async function proxy(request) { export async function proxy(request) {
const pathname = request.nextUrl.pathname const pathname = request.nextUrl.pathname
......
...@@ -182,6 +182,8 @@ module.exports = { ...@@ -182,6 +182,8 @@ module.exports = {
} }
``` ```
> **Good to know:** When [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) is set, Next.js uses a constant build ID and `generateBuildId` has no effect. [Version skew](#version-skew) is detected from the deployment ID instead.
## Multi-Server Deployments ## Multi-Server Deployments
When running Next.js across multiple server instances (for example, containers behind a load balancer), there are additional considerations to ensure consistent behavior. When running Next.js across multiple server instances (for example, containers behind a load balancer), there are additional considerations to ensure consistent behavior.
......
---
title: The Server and Client Boundary
nav_title: Server and Client Boundary
description: Learn where Server and Client Components run in the App Router and how the boundary between them works.
related:
title: Next Steps
description: Learn how to apply this model and where the boundary is defined.
links:
- app/getting-started/server-and-client-components
- app/api-reference/directives/use-client
- app/getting-started/fetching-data
- app/guides/rendering-philosophy
---
React Server Components (RSC) split a component tree between server and client module graphs. This boundary determines where component code runs and whether that code ships to the browser. RSC keeps Server Components exclusively on the server and retains Client Components for interactive UI. Both compose in a single tree, which the server renders into the [RSC Payload](/docs/app/glossary#rsc-payload), a serialized description of the UI that carries references to the Client Components inside it.
Before RSC, React components followed what RSC now calls the Client Component model. React could render these components to HTML on the server, but the same code also shipped to the browser to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) that HTML. Hydration made the initial HTML interactive and required the component to produce matching output on the server and in the browser. Apps rendered entirely on the client could instead begin with an empty shell and mount the component tree in the browser.
```txt
Server Component
├─ Server Component
└─ Client Component
└─ Client Component
```
Each component's module belongs to the server [module graph](/docs/app/glossary#module-graph), the client module graph, or both. Next.js compiles a module used by both graphs separately for each environment.
During rendering, the server graph produces references to Client Components and serializes the props passed to them. The client graph does not import the server graph. The client graph receives the references and serialized props through the RSC Payload.
## Rendering environments
The component names suggest a clean split between server and browser, but rendering happens in both places. On the server, the Server Component tree produces the RSC Payload. Next.js uses the payload and Client Components to render HTML at build time or while handling a request.
When deciding where a component runs, consider both its server render and whether its code runs in the browser:
| | On the server | In the browser |
| -------------------- | ------------- | -------------- |
| **Server Component** | Yes | No |
| **Client Component** | Yes | Yes |
The word "Client" indicates that a Client Component also runs in the browser, alongside its server render.
On a direct visit, the following Client Component renders on the server and again in the browser during hydration. Its log appears in the terminal and the browser console. On a client-side navigation, the server sends the RSC Payload, and the component renders in the browser without server-rendered HTML.
```tsx filename="app/hello.tsx" switcher
'use client'
export default function Hello() {
console.log('Hello rendered') // on a direct visit: server, then browser
return <p>Hello</p>
}
```
```jsx filename="app/hello.js" switcher
'use client'
export default function Hello() {
console.log('Hello rendered') // on a direct visit: server, then browser
return <p>Hello</p>
}
```
Rendering a Client Component on the server produces HTML, but the component remains a Client Component.
Rendering Client Components to HTML predates RSC. Depending on the route, Next.js can generate or regenerate HTML:
- At build time with [Static Site Generation (SSG)](/docs/app/glossary#prerendering).
- After the build with [Incremental Static Regeneration (ISR)](/docs/app/glossary#incremental-static-regeneration-isr).
- For each request with server-side rendering (SSR).
RSC is a separate process that keeps Server Component code on the server and emits the RSC Payload instead of shipping that code. "Server-rendered" describes how Next.js produced the HTML. "Server Component" describes where the component code runs and whether that code ships to the browser.
> **Server Components and SEO**
>
> A crawler that reads only HTML sees the first response and runs none of your JavaScript. Both Server and Client Components contribute HTML to that response.
>
> SEO depends on whether the server render reaches the content. Content gated behind user interaction or an event does not appear in the HTML available to a crawler that does not run JavaScript.
See [Rendering Philosophy](/docs/app/guides/rendering-philosophy) for details about when a component renders, whether at build time or per request, statically or dynamically.
## How data enters the tree
Before RSC, Next.js applications typically gathered server data with functions such as `getStaticProps` or `getServerSideProps`, then passed it to the component tree as props. Data fetching happened before the tree rendered. The tree received data instead of fetching it during render.
```txt
Data
↓
Loader or API
↓
Props
↓
Component tree
```
Because a Server Component runs only on the server, it can access resources such as a database, the filesystem, an internal service, or a secret. The component reads these resources during its own render, without an API route that exposes the data to the client first.
```tsx filename="app/page.tsx" switcher
import { PostList } from '@/app/ui/post-list'
import { getPosts } from '@/lib/data'
export default async function Page() {
const posts = await getPosts() // runs on the server, during render
return <PostList posts={posts} />
}
```
```jsx filename="app/page.js" switcher
import { PostList } from '@/app/ui/post-list'
import { getPosts } from '@/lib/data'
export default async function Page() {
const posts = await getPosts() // runs on the server, during render
return <PostList posts={posts} />
}
```
With RSC, a Server Component can fetch data while rendering. A separate data-loading step does not need to pass initial props to the component tree.
> **Good to know:** Because a Server Component can read secrets and server-only data directly, be deliberate about what you pass to Client Components.
>
> Props are serialized and sent to the browser. See [Data Security](/docs/app/guides/data-security#passing-data-from-server-to-client).
Server Components do not have to await all data before returning UI. To stream server-fetched data into a Client Component, start the request in a Server Component and pass the pending promise as a prop.
The Client Component reads the promise as a resource with [`use`](https://react.dev/reference/react/use#streaming-data-from-server-to-client). While the promise is pending, the nearest [Suspense](/docs/app/glossary#suspense-boundary) boundary shows its fallback. The Client Component renders when the promise resolves.
Because the request starts before the client runs, the Client Component does not need to fetch the same data after mount. You may still need to start a fetch in the browser when the requested data depends on client-only state or user interaction.
Identical `fetch` requests are [memoized during a server render](/docs/app/api-reference/functions/fetch#memoization). With [Cache Components](/docs/app/getting-started/caching), you can cache a data function or component and revalidate that entry independently of the rest of the page. For implementation patterns, see [Fetching Data](/docs/app/getting-started/fetching-data).
## State and interactivity
A Server Component's code never reaches the browser. The component can render again when Next.js renders the route, such as during a navigation, refresh, or after revalidation.
A Client Component's code does reach the browser. React hydrates the component on the initial load, and client-side updates can re-render it in the browser.
> **Good to know:** On the initial load, the RSC Payload ships with the HTML.
>
> Mutating Server Component DOM nodes directly can put the DOM out of sync with React's component tree.
>
> To update Server Component output, render the component again on the server. When the browser receives a new RSC Payload, React reconciles the component tree and updates the DOM. See [Streaming](/docs/app/guides/streaming#the-component-payload).
`useState`, `useEffect`, and event handlers require code that runs in the browser and responds to updates. Server Component code never reaches the browser, so it cannot use these client-side APIs.
Built-in browser and HTML behavior can provide interactivity without a Client Component. For example:
- A `<details>` element opens and closes.
- A `<form>` can submit through a [Server Function](/docs/app/guides/server-actions) passed to its `action` prop.
- A `<video controls>` element plays and pauses.
Use a Client Component when the behavior requires browser state that changes over time, such as a controlled input, live filter, or drag handle. A button or form does not require a Client Component when the browser provides all the required behavior.
For the practical list of what belongs in each environment, see [When to use Server and Client Components](/docs/app/getting-started/server-and-client-components#when-to-use-server-and-client-components).
## Crossing the boundary
You mark a Client Component with the [`'use client'`](/docs/app/api-reference/directives/use-client) directive. The directive draws a boundary in the module graph, and two rules determine what crosses it:
- **Code** crosses through imports. Whatever a Client Component imports is pulled into the [client bundle](/docs/app/glossary#client-bundles).
- **Data** crosses through props, and it must be [serializable](/docs/app/getting-started/server-and-client-components#passing-data-from-server-to-client-components), so functions like event handlers cannot cross.
> **Good to know:**
>
> Passing a function as a prop from a Server Component to a Client Component throws. An event handler like `onClick` cannot cross. A [Server Function](/docs/app/guides/server-actions) marked with `'use server'` crosses as a reference.
>
> A Server Function is not distinguishable from a plain function by its type. The TypeScript plugin allows a Client Component prop typed as a function when its name is `action` or ends in `Action`. The plugin flags other function props.
A rendered React element can cross the boundary because it is serializable data. Passing rendered output as `children` lets a Server Component nest inside a Client Component without importing the Server Component's code into the client graph.
```tsx filename="app/page.tsx" switcher
import { Cart } from '@/app/ui/cart'
import { Modal } from '@/app/ui/modal'
// Page and Cart are Server Components. Modal is a Client Component
export default function Page() {
return (
<Modal title={<div>Your cart</div>}>
<Cart />
</Modal>
)
}
```
```jsx filename="app/page.js" switcher
import { Cart } from '@/app/ui/cart'
import { Modal } from '@/app/ui/modal'
// Page and Cart are Server Components. Modal is a Client Component
export default function Page() {
return (
<Modal title={<div>Your cart</div>}>
<Cart />
</Modal>
)
}
```
The `children` prop behaves like any other prop. `Modal` receives `title` and `children` as serialized React elements, then renders them in the positions defined by its implementation.
```tsx filename="app/ui/modal.tsx" switcher
'use client'
import { useState, type ReactNode } from 'react'
export function Modal({
title,
children,
}: {
title: ReactNode
children: ReactNode
}) {
const [open, setOpen] = useState(true)
if (!open) return null
return (
<div role="dialog">
<header>
{title}
<button onClick={() => setOpen(false)}>Close</button>
</header>
{children}
</div>
)
}
```
```jsx filename="app/ui/modal.js" switcher
'use client'
import { useState } from 'react'
export function Modal({ title, children }) {
const [open, setOpen] = useState(true)
if (!open) return null
return (
<div role="dialog">
<header>
{title}
<button onClick={() => setOpen(false)}>Close</button>
</header>
{children}
</div>
)
}
```
Here, `Cart` runs on the server, and `Modal` only ever sees its output, never its code.
<details>
<summary>Owner and parent</summary>
In this example, `Page` shows two roles React keeps separate:
- The **owner** is the component whose source contains the JSX for a child. `Page` owns both `Modal` and `Cart`.
- The **parent** directly contains the child in the rendered tree. `Modal` is the parent of `Cart`.
Because `Cart`'s owner is a Server Component, `Cart` renders on the server. `Modal` is only the parent, so `Modal` receives `Cart`'s output to place but not its code to run. This separation lets a Client Component display a Server Component it never imported.
</details>
<details>
<summary>Compound components across the boundary</summary>
Compound components can expose subcomponents as static properties, such as `Menu.Item` or `Tabs.Panel`. This pattern works within one graph when all pieces are Server Components or all pieces are Client Components.
The pattern breaks when a static member crosses the boundary. A Server Component that imports a Client Component receives a client reference instead of the function. As a result, `Menu.Item` is `undefined`, and React throws "Element type is invalid."
Use a compound Client Component from another Client Component. To use its pieces from a Server Component, expose them as named exports instead of static properties.
</details>
You only need `'use client'` at the entry to a client subtree, not on every file inside it. Every module imported from that entry becomes part of the client module graph.
To leave a shared component unchanged, create a Client Component wrapper that imports it and place the directive on the wrapper. The wrapper keeps the shared module unchanged and puts the boundary closer to your application code. It also avoids adding the directive to every shared component that calls `useState` or `useEffect`.
If client code enters the server graph without a boundary, the compiler points to where you need the directive.
For more patterns, see [Interleaving Server and Client Components](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components).
For the other directives used in Next.js, see the [directives](/docs/app/api-reference/directives) documentation.
...@@ -5,26 +5,22 @@ description: Next.js fully supports building Single-Page Applications (SPAs). ...@@ -5,26 +5,22 @@ description: Next.js fully supports building Single-Page Applications (SPAs).
related: related:
description: Related guides and references. description: Related guides and references.
links: links:
- app/guides/client-side-data-fetching
- app/guides/interactive-apps - app/guides/interactive-apps
- app/guides/server-actions - app/guides/server-actions
- app/guides/forms - app/guides/forms
- app/guides/streaming - app/guides/streaming
- app/api-reference/components/link
- app/guides/static-exports - app/guides/static-exports
--- ---
Next.js fully supports building Single-Page Applications (SPAs). Build Single-Page Applications (SPAs) with client-side navigation and data fetching. Next.js supports client and server patterns in the same app, and existing SPAs can migrate without a full rewrite.
This includes fast route transitions with prefetching, client-side data fetching, using browser APIs, integrating with third-party client libraries, creating static routes, and more.
If you have an existing SPA, you can migrate to Next.js without large changes to your code. Next.js then allows you to progressively add server features as needed.
## What is a Single-Page Application? ## What is a Single-Page Application?
The definition of a SPA varies. We’ll define a “strict SPA” as: The definition of a SPA varies. We'll define a "strict SPA" as:
- **Client-side rendering (CSR)**: The app is served by one HTML file (e.g. `index.html`). Every route, page transition, and data fetch is handled by JavaScript in the browser. - **Client-side rendering (CSR)**: The app is served by one HTML file (e.g. `index.html`). Every route, page transition, and data fetch is handled by JavaScript in the browser.
- **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page’s DOM and fetches data as needed. - **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page's DOM and fetches data as needed.
Strict SPAs often require large amounts of JavaScript to load before the page can be interactive. Further, client data waterfalls can be challenging to manage. Building SPAs with Next.js can address these issues. Strict SPAs often require large amounts of JavaScript to load before the page can be interactive. Further, client data waterfalls can be challenging to manage. Building SPAs with Next.js can address these issues.
...@@ -34,19 +30,21 @@ Next.js can automatically code split your JavaScript bundles, and generate multi ...@@ -34,19 +30,21 @@ Next.js can automatically code split your JavaScript bundles, and generate multi
The [`next/link`](/docs/app/api-reference/components/link) component automatically [prefetches](/docs/app/api-reference/components/link#prefetch) routes, giving you the fast page transitions of a strict SPA, but with the advantage of persisting application routing state to the URL for linking and sharing. The [`next/link`](/docs/app/api-reference/components/link) component automatically [prefetches](/docs/app/api-reference/components/link#prefetch) routes, giving you the fast page transitions of a strict SPA, but with the advantage of persisting application routing state to the URL for linking and sharing.
Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, Next.js allows you to progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed. Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, you can progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed.
## Examples ## Build common SPA patterns
The following examples cover common patterns for building an SPA with Next.js. The companion [demo](https://next-spa-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/next-spa-patterns)) shows each pattern in action. The following examples cover common patterns for building an SPA with Next.js. The companion [demo](https://next-spa-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/next-spa-patterns)) shows each pattern in action.
### Using React’s `use` within a Context Provider ### Using React's `use` within a Context Provider
You can use React’s [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render. You can use React's [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render.
Starting the request on the server, before the rest of the app renders, lets the response stream immediately and avoids client-side request waterfalls. Starting the request on the server, before the rest of the app renders, lets the response stream immediately and avoids client-side request waterfalls.
You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook. A provider isn't always the best fit: often you can read the data in a Server Component, or pass the Promise directly, rather than putting everything in context. For general client-side data fetching, a library like [SWR](#spas-with-swr) can help. You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook.
When a Client Component needs focus revalidation, polling, mutations, or request deduplication, use a library such as SWR or TanStack Query. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating the library cache with the Next.js server and client caches.
Start the request in a Server Component (here, the root layout) without awaiting it, and pass the Promise to the provider: Start the request in a Server Component (here, the root layout) without awaiting it, and pass the Promise to the provider:
...@@ -154,7 +152,7 @@ export function Profile() { ...@@ -154,7 +152,7 @@ export function Profile() {
const userPromise = useUser() const userPromise = useUser()
const user = use(userPromise) const user = use(userPromise)
return '...' return <p>{user.name}</p>
} }
``` ```
...@@ -168,13 +166,11 @@ export function Profile() { ...@@ -168,13 +166,11 @@ export function Profile() {
const userPromise = useUser() const userPromise = useUser()
const user = use(userPromise) const user = use(userPromise)
return '...' return <p>{user.name}</p>
} }
``` ```
You can also move the `use()` call into the `useUser` hook so components just call `const user = useUser()`. That reads cleanly, but calling `use()` in the component keeps it clear where the component suspends. Wrap the consumer in a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary to show a fallback while the Promise resolves:
Wrap the consumer in a `<Suspense>` boundary to show a fallback while the Promise resolves:
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -206,325 +202,6 @@ The component that consumes the Promise (e.g. `Profile` above) suspends while th ...@@ -206,325 +202,6 @@ The component that consumes the Promise (e.g. `Profile` above) suspends while th
See the [live demo](https://next-spa-patterns.labs.vercel.dev/use-context) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/use-context). See the [live demo](https://next-spa-patterns.labs.vercel.dev/use-context) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/use-context).
### SPAs with SWR
[SWR](https://swr.vercel.app) is a popular React library for data fetching.
With SWR 2.3.0 (and React 19+), you can gradually adopt server features alongside your existing SWR-based client data fetching code. This is an abstraction of the above `use()` pattern. This means you can move data fetching between the client and server-side, or use both:
- **Client-only:** `useSWR(key, fetcher)`
- **Server-only:** `useSWR(key)` + RSC-provided data
- **Mixed:** `useSWR(key, fetcher)` + RSC-provided data
Reach for SWR when you need its client-side features, such as revalidation on focus or interval, [`mutate`](https://swr.vercel.app/docs/mutation), or request deduplication across components. If a Client Component only needs to read server data once, pass a Promise to it and unwrap it with [`use()`](#using-reacts-use-within-a-context-provider) instead. That avoids adding a data-fetching library for data that never revalidates on the client.
To provide server data to SWR on the first render, wrap your application in `<SWRConfig>` and provide a `fallback`:
```tsx filename="app/layout.tsx" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
```js filename="app/layout.js" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
Because this is a Server Component, `getUser()` can securely read cookies, headers, or talk to your database. No separate API route is needed. Client components below the `<SWRConfig>` can call `useSWR()` with the same key to retrieve the user data. The component code with `useSWR` **does not require any changes** from your existing client-fetching solution.
```tsx filename="app/profile.tsx" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url: string) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
```jsx filename="app/profile.js" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
The `fallback` data can be prerendered and included in the initial HTML response, then immediately read in the child components using `useSWR`. SWR’s polling, revalidation, and caching still run **client-side only**, so it preserves all the interactivity you rely on for an SPA.
Because Next.js seeds the `fallback` on the server, `useSWR` has data on first render, so there's no need for conditional logic to handle an `undefined` `data`. The seeded data counts as loaded, so [`isLoading`](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux) stays `false`. A client-side revalidation surfaces as `isValidating` instead, which you can use to show a background-refresh indicator.
| | SWR | RSC | RSC + SWR |
| -------------------- | ------------------- | ------------------- | ------------------- |
| SSR data | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Streaming while SSR | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Deduplicate requests | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Client-side features | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> |
#### Scoping server data to the components that use it
`<SWRConfig>` can live in any Server Component, not only the root layout. Placing it on the route segment that owns the data keeps the `fallback` close to where it is read, keeps unrelated keys out of a global config, and lets each segment start its own server-side requests. Nested `<SWRConfig>` providers merge their fallbacks, so a page-level config extends the keys seeded by a parent layout rather than replacing them:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
Inside `<Suspense>`, `params.then()` resolves the `id` and passes it to `ProjectData`, which seeds the `fallback` with the `getProject(id)` promise. Only that subtree suspends while the data loads.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then((res) => res.json())
export function ProjectView({ id }: { id: string }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
export function ProjectView({ id }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly, since SWR looks up the seeded value by key. Nothing warns on a mismatch: the seeded value is never read, `data` starts as `undefined`, and SWR fetches again on the client. When a key is built from dynamic values (route params, search params), derive it in one shared place so the server and client cannot drift apart. `fallback` seeds the first render, not SWR's persistent cache, so use [`preload`](https://swr.vercel.app/docs/prefetching) to fill the cache and reuse the request on revalidation.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/swr).
### SPAs with TanStack Query
You can use [TanStack Query](https://tanstack.com/query) (formerly React Query) with Next.js on the client and the server, and seed its cache from a Server Component the same way as [SWR](#spas-with-swr): prefetch on the server, hand the cache to the client, and let it own revalidation from there.
TanStack Query needs a one-time setup, including a `getQueryClient` (new per request on the server, a singleton in the browser), a `<QueryClientProvider>`, and a client configured to dehydrate pending queries. TanStack Query owns this integration, so follow [its Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) for the full setup and current APIs.
A Server Component starts the request with `prefetchQuery` **without awaiting it**, then serializes the cache into the streamed HTML with `<HydrationBoundary>`:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProjectData` prefetches below the boundary.
The Client Component reads the data with the same query key. Use `useSuspenseQuery` when a `<Suspense>` boundary handles loading and you want `data` to always be defined. Use `useQuery` when you would rather render its `isPending` and `error` states inline:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }: { id: string }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
The query key connects the two sides, the same way the matching `fallback` and `useSWR` keys do above.
> **Good to know:** When you cache this data with [Cache Components](/docs/app/getting-started/caching), add [`"use cache"`](/docs/app/api-reference/directives/use-cache) to the data function (such as `getProject`), not around `dehydrate()`. Caching the dehydrated state also caches TanStack Query metadata such as timestamps, which can serve stale data on later requests.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query).
### Rendering components only in the browser ### Rendering components only in the browser
Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/guides/lazy-loading#nextdynamic): Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/guides/lazy-loading#nextdynamic):
...@@ -545,9 +222,9 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/browser-only) and ...@@ -545,9 +222,9 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/browser-only) and
If you are migrating from a strict SPA like [Create React App](/docs/app/guides/migrating/from-create-react-app) or [Vite](/docs/app/guides/migrating/from-vite), you might have existing code which shallow routes to update the URL state. This can be useful for manual transitions between views in your application _without_ using the default Next.js file-system routing. If you are migrating from a strict SPA like [Create React App](/docs/app/guides/migrating/from-create-react-app) or [Vite](/docs/app/guides/migrating/from-vite), you might have existing code which shallow routes to update the URL state. This can be useful for manual transitions between views in your application _without_ using the default Next.js file-system routing.
Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page. Next.js lets you use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). The `pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).
```tsx filename="app/ui/sort-products.tsx" switcher ```tsx filename="app/ui/sort-products.tsx" switcher
'use client' 'use client'
...@@ -601,7 +278,7 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/shallow-routing) a ...@@ -601,7 +278,7 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/shallow-routing) a
### Mutating data with Server Actions ### Mutating data with Server Actions
The sections above seed client-side data-fetching libraries from the server, which handle reads. Interactivity means writing data, and that usually happens outside those libraries: a Client Component calls a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. If you already use SWR or TanStack Query, you can instead write through an API route and revalidate with SWR's [`mutate`](https://swr.vercel.app/docs/mutation) or TanStack Query's [`invalidateQueries`](https://tanstack.com/query/latest/docs/framework/react/guides/invalidations-from-mutations). The rest of this section uses Server Actions directly. Interactivity often requires writing data. A Client Component can call a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. A client data-fetching library can coordinate an optimistic browser update around the same Server Action, as shown in the [client-side data fetching guide](/docs/app/guides/client-side-data-fetching#coordinate-mutations). The rest of this section coordinates the Server Action with React's built-in state APIs.
A Server Action takes time and can fail. React has useful tools to keep the UI responsive while it runs, so a mutation can feel as instant as a client-rendered SPA: [transitions](https://react.dev/reference/react/useTransition), [`useOptimistic`](https://react.dev/reference/react/useOptimistic), [`useActionState`](https://react.dev/reference/react/useActionState), and [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus). A Server Action takes time and can fail. React has useful tools to keep the UI responsive while it runs, so a mutation can feel as instant as a client-rendered SPA: [transitions](https://react.dev/reference/react/useTransition), [`useOptimistic`](https://react.dev/reference/react/useOptimistic), [`useActionState`](https://react.dev/reference/react/useActionState), and [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus).
...@@ -649,7 +326,7 @@ export function DeletePost({ id }) { ...@@ -649,7 +326,7 @@ export function DeletePost({ id }) {
For list-like state where each change should appear instantly, you can combine `useActionState` with `useOptimistic`. The example below is a to-do list: a pure reducer defines how each action changes the list, so the client and server share one copy of that logic: For list-like state where each change should appear instantly, you can combine `useActionState` with `useOptimistic`. The example below is a to-do list: a pure reducer defines how each action changes the list, so the client and server share one copy of that logic:
```ts filename="app/reducer.ts" switcher ```ts filename="app/todos-reducer.ts" switcher
export type Todo = { id: string; text: string; done: boolean } export type Todo = { id: string; text: string; done: boolean }
export type TodoAction = export type TodoAction =
...@@ -658,7 +335,7 @@ export type TodoAction = ...@@ -658,7 +335,7 @@ export type TodoAction =
| { type: 'edit'; id: string; text: string } | { type: 'edit'; id: string; text: string }
| { type: 'delete'; id: string } | { type: 'delete'; id: string }
export function applyAction(todos: Todo[], action: TodoAction): Todo[] { export function todosReducer(todos: Todo[], action: TodoAction): Todo[] {
switch (action.type) { switch (action.type) {
case 'add': case 'add':
return [...todos, { id: action.id, text: action.text, done: false }] return [...todos, { id: action.id, text: action.text, done: false }]
...@@ -678,8 +355,8 @@ export function applyAction(todos: Todo[], action: TodoAction): Todo[] { ...@@ -678,8 +355,8 @@ export function applyAction(todos: Todo[], action: TodoAction): Todo[] {
} }
``` ```
```js filename="app/reducer.js" switcher ```js filename="app/todos-reducer.js" switcher
export function applyAction(todos, action) { export function todosReducer(todos, action) {
switch (action.type) { switch (action.type) {
case 'add': case 'add':
return [...todos, { id: action.id, text: action.text, done: false }] return [...todos, { id: action.id, text: action.text, done: false }]
...@@ -705,13 +382,13 @@ The Server Action applies the reducer, persists the result, and returns the next ...@@ -705,13 +382,13 @@ The Server Action applies the reducer, persists the result, and returns the next
'use server' 'use server'
import { db } from './db' import { db } from './db'
import { applyAction, type Todo, type TodoAction } from './reducer' import { todosReducer, type Todo, type TodoAction } from './todos-reducer'
export async function todosReducer( export async function saveTodos(
todos: Todo[], todos: Todo[],
action: TodoAction action: TodoAction
): Promise<Todo[]> { ): Promise<Todo[]> {
const next = applyAction(todos, action) const next = todosReducer(todos, action)
await db.saveTodos(next) await db.saveTodos(next)
return next return next
} }
...@@ -721,10 +398,10 @@ export async function todosReducer( ...@@ -721,10 +398,10 @@ export async function todosReducer(
'use server' 'use server'
import { db } from './db' import { db } from './db'
import { applyAction } from './reducer' import { todosReducer } from './todos-reducer'
export async function todosReducer(todos, action) { export async function saveTodos(todos, action) {
const next = applyAction(todos, action) const next = todosReducer(todos, action)
await db.saveTodos(next) await db.saveTodos(next)
return next return next
} }
...@@ -736,15 +413,12 @@ The client passes the same reducer to `useOptimistic`, so the optimistic update ...@@ -736,15 +413,12 @@ The client passes the same reducer to `useOptimistic`, so the optimistic update
'use client' 'use client'
import { useActionState, useOptimistic, startTransition } from 'react' import { useActionState, useOptimistic, startTransition } from 'react'
import { todosReducer } from './actions' import { saveTodos } from './actions'
import { applyAction, type Todo, type TodoAction } from './reducer' import { todosReducer, type Todo, type TodoAction } from './todos-reducer'
export function TodoList({ initialTodos }: { initialTodos: Todo[] }) { export function TodoList({ initialTodos }: { initialTodos: Todo[] }) {
const [todos, dispatch, isPending] = useActionState( const [todos, dispatch, isPending] = useActionState(saveTodos, initialTodos)
todosReducer, const [optimisticTodos, addOptimistic] = useOptimistic(todos, todosReducer)
initialTodos
)
const [optimisticTodos, addOptimistic] = useOptimistic(todos, applyAction)
function runAction(action: TodoAction) { function runAction(action: TodoAction) {
startTransition(() => { startTransition(() => {
...@@ -796,15 +470,12 @@ export function TodoList({ initialTodos }: { initialTodos: Todo[] }) { ...@@ -796,15 +470,12 @@ export function TodoList({ initialTodos }: { initialTodos: Todo[] }) {
'use client' 'use client'
import { useActionState, useOptimistic, startTransition } from 'react' import { useActionState, useOptimistic, startTransition } from 'react'
import { todosReducer } from './actions' import { saveTodos } from './actions'
import { applyAction } from './reducer' import { todosReducer } from './todos-reducer'
export function TodoList({ initialTodos }) { export function TodoList({ initialTodos }) {
const [todos, dispatch, isPending] = useActionState( const [todos, dispatch, isPending] = useActionState(saveTodos, initialTodos)
todosReducer, const [optimisticTodos, addOptimistic] = useOptimistic(todos, todosReducer)
initialTodos
)
const [optimisticTodos, addOptimistic] = useOptimistic(todos, applyAction)
function runAction(action) { function runAction(action) {
startTransition(() => { startTransition(() => {
...@@ -863,7 +534,7 @@ To learn more about adding interactivity on top of server-rendered apps so they ...@@ -863,7 +534,7 @@ To learn more about adding interactivity on top of server-rendered apps so they
Next.js also supports generating a fully [static site](/docs/app/guides/static-exports). This has some advantages over strict SPAs: Next.js also supports generating a fully [static site](/docs/app/guides/static-exports). This has some advantages over strict SPAs:
- **Automatic code-splitting**: Instead of shipping a single `index.html`, Next.js will generate an HTML file per route, so your visitors get the content faster without waiting for the client JavaScript bundle. - **Automatic code-splitting**: Instead of shipping a single `index.html`, Next.js will generate an HTML file per route, so your visitors get the content faster without waiting for the client JavaScript bundle.
- **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions remain instant and SPA-like. - **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions are still instant and SPA-like.
To enable a static export, update your configuration: To enable a static export, update your configuration:
......
...@@ -232,15 +232,19 @@ export default function Page() { ...@@ -232,15 +232,19 @@ export default function Page() {
### Route Handlers ### Route Handlers
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. For example: Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. To ensure Route Handlers are prerendered, you must explicitly mark the handler as static by adding `export const dynamic = 'force-static'` when a static export is enabled. For example:
```ts filename="app/data.json/route.ts" switcher ```ts filename="app/data.json/route.ts" switcher
export const dynamic = 'force-static'
export async function GET() { export async function GET() {
return Response.json({ name: 'Lee' }) return Response.json({ name: 'Lee' })
} }
``` ```
```js filename="app/data.json/route.js" switcher ```js filename="app/data.json/route.js" switcher
export const dynamic = 'force-static'
export async function GET() { export async function GET() {
return Response.json({ name: 'Lee' }) return Response.json({ name: 'Lee' })
} }
......
...@@ -36,7 +36,7 @@ When a browser requests a page, two streams work together during the initial pag ...@@ -36,7 +36,7 @@ When a browser requests a page, two streams work together during the initial pag
### The HTML stream ### The HTML stream
React's server renderer produces progressive HTML chunks. The static parts of your page (layouts, navigation, Suspense fallbacks) render first and are sent immediately. When an async [Server Component](/docs/app/glossary#server-component) resolves, React streams its completed HTML along with inline `<script>` tags: one that swaps the fallback DOM node with the new content, and another carrying the [component payload](#the-component-payload) so React can later hydrate it. The browser executes the swap instantly, without waiting for the page's JavaScript bundle to load or hydration to complete. This is what the user _sees_: the page painting progressively, section by section. React's server renderer produces progressive HTML chunks. The static parts of your page (layouts, navigation, Suspense fallbacks) render first and are sent immediately. When a `<Suspense>` boundary's content is ready, for example when an async [Server Component](/docs/app/glossary#server-component) resolves, React streams its completed HTML along with inline `<script>` tags: one that swaps the fallback DOM node with the new content, and another carrying the [component payload](#the-component-payload) so React can later hydrate it. The browser executes the swap instantly, without waiting for the page's JavaScript bundle to load or hydration to complete. This is what the user _sees_: the page painting progressively, section by section.
### The component payload ### The component payload
...@@ -579,11 +579,17 @@ Without streaming, the server waits for all data before sending any HTML, so TTF ...@@ -579,11 +579,17 @@ Without streaming, the server waits for all data before sending any HTML, so TTF
### LCP (Largest Contentful Paint) ### LCP (Largest Contentful Paint)
If your LCP element (a hero image, a main heading, a product photo) is inside a Suspense boundary, it can't paint until that boundary resolves. To keep LCP fast: If your LCP element (a hero image, a main heading, a product photo) is inside a Suspense boundary, it can't paint until that boundary's content is swapped in. The element then depends on the work the server does to render it, not on your initial server response time. Revealing it costs something on the client too, because React streams a small inline script alongside the boundary's HTML and the content only appears once that script runs.
Data fetching is not the only reason a boundary delays your LCP element. React also holds back a large boundary, because sending its HTML takes time. See [what activates a Suspense boundary](https://react.dev/reference/react/Suspense#what-activates-a-suspense-boundary).
> **Good to know:** As a rule of thumb, if there's a Suspense boundary, React might use it. Under a slow network or a busy CPU, concurrent rendering can fall back to it even when you didn't expect it. Adding a boundary means accepting that, so don't add one you don't need.
To keep LCP fast:
- Keep LCP elements **outside** or **above** Suspense boundaries so they render as part of the static shell. - Keep LCP elements **outside** or **above** Suspense boundaries so they render as part of the static shell.
- Use the [`preload`](/docs/app/api-reference/components/image#preload) prop on `next/image` for LCP images. This injects a `<link rel="preload">` into the `<head>`, so the browser starts fetching the image from the very first chunk, before the `<img>` tag even appears in the HTML. - Use the [`preload`](/docs/app/api-reference/components/image#preload) prop on `next/image` for LCP images. This injects a `<link rel="preload">` into the `<head>`, so the browser starts fetching the image from the very first chunk, before the `<img>` tag even appears in the HTML. It controls when the image is fetched, not when it paints. An image inside a boundary still waits for the swap.
- For non-image LCP elements (text, headings), make sure they are not wrapped in a Suspense boundary that depends on slow data. - For non-image LCP elements (text, headings), render them outside Suspense boundaries.
### CLS (Cumulative Layout Shift) ### CLS (Cumulative Layout Shift)
......
...@@ -70,7 +70,7 @@ yarn create jest@latest ...@@ -70,7 +70,7 @@ yarn create jest@latest
bun create jest@latest bun create jest@latest
``` ```
This will take you through a series of prompts to setup Jest for your project, including automatically creating a `jest.config.ts|js` file. This will take you through a series of prompts to set up Jest for your project, including automatically creating a `jest.config.ts|js` file.
Update your config file to use `next/jest`. This transformer has all the necessary configuration options for Jest to work with Next.js: Update your config file to use `next/jest`. This transformer has all the necessary configuration options for Jest to work with Next.js:
......
...@@ -46,7 +46,7 @@ yarn create playwright ...@@ -46,7 +46,7 @@ yarn create playwright
bun create playwright bun create playwright
``` ```
This will take you through a series of prompts to setup and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide. This will take you through a series of prompts to set up and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide.
## Creating your first Playwright E2E test ## Creating your first Playwright E2E test
......
...@@ -4,7 +4,7 @@ nav_title: Vitest ...@@ -4,7 +4,7 @@ nav_title: Vitest
description: Learn how to set up Vitest with Next.js for Unit Testing. description: Learn how to set up Vitest with Next.js for Unit Testing.
--- ---
Vitest and React Testing Library are frequently used together for **Unit Testing**. This guide will show you how to setup Vitest with Next.js and write your first tests. Vitest and React Testing Library are frequently used together for **Unit Testing**. This guide will show you how to set up Vitest with Next.js and write your first tests.
> **Good to know:** Since `async` Server Components are new to the React ecosystem, Vitest currently does not support them. While you can still run **unit tests** for synchronous Server and Client Components, we recommend using **E2E tests** for `async` components. > **Good to know:** Since `async` Server Components are new to the React ecosystem, Vitest currently does not support them. While you can still run **unit tests** for synchronous Server and Client Components, we recommend using **E2E tests** for `async` components.
......
...@@ -76,7 +76,9 @@ npx @next/codemod upgrade canary --yes ...@@ -76,7 +76,9 @@ npx @next/codemod upgrade canary --yes
npx @next/codemod@canary cache-components-instant-false ./app npx @next/codemod@canary cache-components-instant-false ./app
``` ```
This codemod adds `export const instant = false` to every `app/**/{page,layout,default}` file that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`. This codemod adds `export const instant = false` to every `{page,layout,default}` file in your app directory that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`.
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
```diff filename="app/page.tsx" ```diff filename="app/page.tsx"
+ // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. + // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
...@@ -98,7 +100,9 @@ See the [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-comp ...@@ -98,7 +100,9 @@ See the [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-comp
npx @next/codemod@canary remove-partial-prefetch ./app npx @next/codemod@canary remove-partial-prefetch ./app
``` ```
This codemod removes `export const prefetch = 'partial'` from `app/**/{page,layout}` files, so you can enable [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) globally and then drop the now-redundant per-route opt-ins. It removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place. This codemod removes `export const prefetch = 'partial'` from the `{page,layout}` files in your app directory, so you can enable [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) globally and then drop the now-redundant per-route opt-ins. It removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place.
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
```diff filename="app/products/[slug]/page.tsx" ```diff filename="app/products/[slug]/page.tsx"
- export const prefetch = 'partial' - export const prefetch = 'partial'
......
...@@ -602,7 +602,7 @@ To continue using Speed Insights, follow the [Vercel Speed Insights Quickstart]( ...@@ -602,7 +602,7 @@ To continue using Speed Insights, follow the [Vercel Speed Insights Quickstart](
The `geo` and `ip` properties on `NextRequest` have been removed as these values are provided by your hosting provider. A [codemod](/docs/app/guides/upgrading/codemods#150) is available to automate this migration. The `geo` and `ip` properties on `NextRequest` have been removed as these values are provided by your hosting provider. A [codemod](/docs/app/guides/upgrading/codemods#150) is available to automate this migration.
If you are using Vercel, you can alternatively use the `geolocation` and `ipAddress` functions from [`@vercel/functions`](https://vercel.com/docs/functions/vercel-functions-package) instead: If you are using Vercel, you can alternatively use the `geolocation` and `ipAddress` functions from [`@vercel/functions`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package) instead:
```ts filename="middleware.ts" ```ts filename="middleware.ts"
import { geolocation } from '@vercel/functions' import { geolocation } from '@vercel/functions'
......
...@@ -276,7 +276,7 @@ export default nextConfig ...@@ -276,7 +276,7 @@ export default nextConfig
### Turbopack File System Caching ### Turbopack File System Caching
Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`. See [`turbopackFileSystemCache`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable it. Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`, through `experimental.turbopackFileSystemCacheForDev` and `experimental.turbopackFileSystemCacheForBuild`. See [Turbopack FileSystem Caching](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable either one.
## Async Request APIs (Breaking change) ## Async Request APIs (Breaking change)
...@@ -1074,7 +1074,7 @@ const nextConfig = { ...@@ -1074,7 +1074,7 @@ const nextConfig = {
}, },
} }
export default nextConfig module.exports = nextConfig
``` ```
Evaluate if AMP is still necessary for your use case. Most performance benefits can now be achieved through Next.js's built-in optimizations and modern web standards. Evaluate if AMP is still necessary for your use case. Most performance benefits can now be achieved through Next.js's built-in optimizations and modern web standards.
......
...@@ -163,13 +163,13 @@ Self-hosting videos may be preferable for several reasons: ...@@ -163,13 +163,13 @@ Self-hosting videos may be preferable for several reasons:
### Using Vercel Blob for video hosting ### Using Vercel Blob for video hosting
[Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob: [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob:
**1. Uploading a video to Vercel Blob** **1. Uploading a video to Vercel Blob**
In your Vercel dashboard, navigate to the "Storage" tab and select your [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table. In your Vercel dashboard, navigate to the "Storage" tab and select your [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table.
Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on [server-side uploads](https://vercel.com/docs/storage/vercel-blob/server-upload). Vercel also supports [client-side uploads](https://vercel.com/docs/storage/vercel-blob/client-upload). This method may be preferable for certain use cases. Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on [server-side uploads](https://vercel.com/docs/vercel-blob/server-upload). Vercel also supports [client-side uploads](https://vercel.com/docs/vercel-blob/client-upload). This method may be preferable for certain use cases.
**2. Displaying the video in Next.js** **2. Displaying the video in Next.js**
...@@ -207,7 +207,7 @@ In this approach, the page uses the video's `@vercel/blob` URL to display the vi ...@@ -207,7 +207,7 @@ In this approach, the page uses the video's `@vercel/blob` URL to display the vi
### Adding subtitles to your video ### Adding subtitles to your video
If you have subtitles for your video, you can easily add them using the `<track>` element inside your `<video>` tag. You can fetch the subtitle file from [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) in a similar way as the video file. Here's how you can update the `<VideoComponent>` to include subtitles. If you have subtitles for your video, you can easily add them using the `<track>` element inside your `<video>` tag. You can fetch the subtitle file from [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) in a similar way as the video file. Here's how you can update the `<VideoComponent>` to include subtitles.
```jsx filename="app/page.jsx" ```jsx filename="app/page.jsx"
async function VideoComponent({ fileName }) { async function VideoComponent({ fileName }) {
...@@ -237,13 +237,13 @@ To continue learning more about video optimization and best practices, please re ...@@ -237,13 +237,13 @@ To continue learning more about video optimization and best practices, please re
- **Understanding video formats and codecs**: Choose the right format and codec, like MP4 for compatibility or WebM for web optimization, for your video needs. For more details, see [Mozilla's guide on video codecs](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs). - **Understanding video formats and codecs**: Choose the right format and codec, like MP4 for compatibility or WebM for web optimization, for your video needs. For more details, see [Mozilla's guide on video codecs](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs).
- **Video compression**: Use tools like FFmpeg to effectively compress videos, balancing quality with file size. Learn about compression techniques at [FFmpeg's official website](https://www.ffmpeg.org/). - **Video compression**: Use tools like FFmpeg to effectively compress videos, balancing quality with file size. Learn about compression techniques at [FFmpeg's official website](https://www.ffmpeg.org/).
- **Resolution and bitrate adjustment**: Adjust [resolution and bitrate](https://www.dacast.com/blog/bitrate-vs-resolution/#:~:text=The%20two%20measure%20different%20aspects,yield%20different%20qualities%20of%20video) based on the viewing platform, with lower settings for mobile devices. - **Resolution and bitrate adjustment**: Adjust [resolution and bitrate](https://www.dacast.com/blog/bitrate-vs-resolution/#:~:text=The%20two%20measure%20different%20aspects,yield%20different%20qualities%20of%20video) based on the viewing platform, with lower settings for mobile devices.
- **Content Delivery Networks (CDNs)**: Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. [Learn more](https://vercel.com/docs/edge-network/overview?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) about CDNs and their benefits. - **Content Delivery Networks (CDNs)**: Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. [Learn more](https://vercel.com/docs/cdn?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) about CDNs and their benefits.
Explore these video streaming platforms for integrating video into your Next.js projects: Explore these video streaming platforms for integrating video into your Next.js projects:
### Open source `next-video` component ### Open source `next-video` component
- Provides a `<Video>` component for Next.js, compatible with various hosting services including [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), S3, Backblaze, and Mux. - Provides a `<Video>` component for Next.js, compatible with various hosting services including [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), S3, Backblaze, and Mux.
- [Detailed documentation](https://next-video.dev/docs) for using `next-video.dev` with different hosting services. - [Detailed documentation](https://next-video.dev/docs) for using `next-video.dev` with different hosting services.
### Cloudinary Integration ### Cloudinary Integration
......
...@@ -12,22 +12,28 @@ React's `<ViewTransition>` component integrates with the browser's [View Transit ...@@ -12,22 +12,28 @@ React's `<ViewTransition>` component integrates with the browser's [View Transit
This guide walks through four patterns that cover the most common cases: morphing shared elements, animating loading states, adding directional navigation, and crossfading content within the same route. This guide walks through four patterns that cover the most common cases: morphing shared elements, animating loading states, adding directional navigation, and crossfading content within the same route.
## Use the vercel-react-view-transitions skill ## Add view transitions with an agent
The [`vercel-react-view-transitions`](https://github.com/vercel-labs/agent-skills/tree/main/skills/react-view-transitions) skill teaches a coding agent the patterns in this guide, plus the CSS recipes and troubleshooting for applying them to an existing app. The [`vercel-react-view-transitions`](https://skills.sh/vercel-labs/agent-skills/vercel-react-view-transitions) skill teaches a coding agent the patterns in this guide, plus the CSS recipes and troubleshooting for applying them to an existing app.
Install the skill: Install the skill:
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add https://github.com/vercel-labs/agent-skills --skill vercel-react-view-transitions npx skills add vercel-labs/agent-skills --skill vercel-react-view-transitions
``` ```
Then give the agent this prompt: Then prompt the agent with something like:
```prompt ```prompt
Add view transitions to this app using the vercel-react-view-transitions skill. Add view transitions to this app using the vercel-react-view-transitions skill.
``` ```
Or prompt for a specific transition, such as:
- Morphing a thumbnail into a hero image
- Sliding between routes forward and back
- Crossfading content within the same route
To apply the patterns yourself, follow the walkthrough below. To apply the patterns yourself, follow the walkthrough below.
## Example ## Example
......
--- ---
title: Directives title: Directives
description: Directives are used to modify the behavior of your Next.js application. description: Learn how React and Next.js directives define client entry points, Server Functions, and cached output.
--- ---
The following directives are available: Directives are string literals that tell the compiler and bundler how to treat the code around them. On their own, directives look like plain strings, but Next.js and React read them as instructions that transform the code they cover. A directive can create a client entry point or a Server Function, or cache a function's or component's output.
| Directive | Defined by | Effect |
| --------------------------------------------------------------- | ---------- | --------------------------------------------------- |
| [`'use client'`](/docs/app/api-reference/directives/use-client) | React | Creates a client entry point from Server Components |
| [`'use server'`](/docs/app/api-reference/directives/use-server) | React | Exposes server-side functions as Server Functions |
| [`'use cache'`](/docs/app/api-reference/directives/use-cache) | Next.js | Caches and reuses output based on the code's inputs |
The `'use cache'` directive also has [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) and [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private) variants. Configure custom [cache handlers](/docs/app/api-reference/config/next-config-js/cacheHandlers) to control where cached entries are stored.
> **Good to know:** Next.js applies directives during compilation in both development and production.
>
> The error overlay, indicators, and stack traces point to your source file and line rather than the generated output.
## Where to place a directive
The `'use client'` directive must appear at the top of a file, before any imports. It applies to the entire module and defines a file-wide boundary because the module is bundled and shipped to the browser. You cannot use `'use client'` inline.
Place `'use server'` or `'use cache'` at the top of a file to apply the directive to every export. Place either directive at the top of a function to apply it only to that function.
```ts filename="app/data.ts" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id: string) {
return { id }
}
```
```js filename="app/data.js" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id) {
return { id }
}
```
```tsx filename="app/user.tsx" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
```jsx filename="app/user.js" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
Declare `'use server'` and `'use cache'` in server modules, not in a `'use client'` module.
To import a `'use server'` or `'use cache'` function into a Client Component, place the directive at the top of the server module. The Client Component receives a reference that invokes the function on the server.
Place the directive inside a function when it should apply only to that function or component. When it should apply to several exported functions, place it at the top of the file instead of repeating it.
Every exported function covered by a file-level `'use server'` or `'use cache'` directive must be `async`.
## What each directive requires
A directive imposes rules on the code it covers:
- **`'use client'`** marks its exports as the boundary between server and client. Client Component props that cross the boundary must be [serializable](https://react.dev/reference/rsc/use-client#serializable-types). Ordinary functions, such as event handlers, cannot cross, but Server Functions can cross as references.
- **`'use server'`** marks the functions it covers as [Server Functions](/docs/app/glossary#server-function). Server Functions must be `async`. When invoked from a Client Component, their arguments and return values are serialized across the network. The Client Component receives a reference that invokes the function on the server, not the function's code.
- **`'use cache'`** caches the output of the functions or components it covers based on their inputs. Cached functions and components must be `async`. Their arguments and return values must be serializable, except for non-serializable values that the cached code passes through without inspecting. Cached code cannot read request-time APIs like `cookies()`, `headers()`, or `searchParams` directly.
With `'use cache'` at the top of a page or layout file, exported functions such as `generateMetadata` and `generateStaticParams` must be `async`.
## Placement decides what you cache
With `'use cache'`, placement determines the scope of a cache entry. A directive at the top of a page caches the page's output and the components it imports. The same directive inside a data function caches only that function's result. When one data request performs the expensive work, cache that function instead of the page.
With [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote), a remote cache handler stores entries. Larger entries can increase storage and network costs.
...@@ -44,13 +44,11 @@ const nextConfig = { ...@@ -44,13 +44,11 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
} }
export default nextConfig module.exports = nextConfig
``` ```
Then add `'use cache: private'` to your function along with a `cacheLife` configuration. Then add `'use cache: private'` to your function along with a `cacheLife` configuration.
> **Good to know**: This directive is not available in Route Handlers.
### Basic example ### Basic example
In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope: In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope:
...@@ -151,7 +149,7 @@ async function getRecommendations(productId) { ...@@ -151,7 +149,7 @@ async function getRecommendations(productId) {
} }
``` ```
> **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details. > **Good to know**: The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
## Request APIs allowed in private caches ## Request APIs allowed in private caches
......
...@@ -44,7 +44,7 @@ const nextConfig = { ...@@ -44,7 +44,7 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
} }
export default nextConfig module.exports = nextConfig
``` ```
Then add `'use cache: remote'` to the functions or components where you've determined remote caching is justified. The handler implementation is configured via [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers), though hosting providers should typically provide this automatically. If you're self-hosting, see the `cacheHandlers` configuration reference to set up your cache storage. Then add `'use cache: remote'` to the functions or components where you've determined remote caching is justified. The handler implementation is configured via [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers), though hosting providers should typically provide this automatically. If you're self-hosting, see the `cacheHandlers` configuration reference to set up your cache storage.
......
...@@ -45,14 +45,15 @@ const nextConfig = { ...@@ -45,14 +45,15 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
Then, add `use cache` at the file, component, or function level. All functions and components using `use cache` must be async. When used at file level, every exported function becomes a cached function and must also be async: Then, add `use cache` at the function, component, or file level. Cached functions and components must be async:
```tsx ```tsx
// File level // Function level
'use cache' export async function getData() {
'use cache'
export default async function Page() { const res = await fetch('https://api.example.com/data')
// ... const data = await res.json()
return data
} }
// Component level // Component level
...@@ -60,12 +61,16 @@ export async function MyComponent() { ...@@ -60,12 +61,16 @@ export async function MyComponent() {
'use cache' 'use cache'
return <></> return <></>
} }
```
// Function level When used at file level, every exported function becomes a cached function and must also be async:
export async function getData() {
'use cache' ```tsx
const data = await fetch('/api/data') // File level
return data 'use cache'
export default async function Page() {
// ...
} }
``` ```
...@@ -87,7 +92,10 @@ async function Component({ userId }: { userId: string }) { ...@@ -87,7 +92,10 @@ async function Component({ userId }: { userId: string }) {
const getData = async (filter: string) => { const getData = async (filter: string) => {
'use cache' 'use cache'
// Cache key includes both userId (from closure) and filter (argument) // Cache key includes both userId (from closure) and filter (argument)
return fetch(`/api/users/${userId}/data?filter=${filter}`) const res = await fetch(
`https://api.example.com/users/${userId}/data?filter=${filter}`
)
return res.json()
} }
return getData('active') return getData('active')
...@@ -98,6 +106,43 @@ In the snippet above, `userId` is captured from the outer scope and `filter` is ...@@ -98,6 +106,43 @@ In the snippet above, `userId` is captured from the outer scope and `filter` is
> **Good to know:** When a cached function reads [root parameters](/docs/app/api-reference/functions/next-root-params), only the ones it actually reads become part of its cache key. > **Good to know:** When a cached function reads [root parameters](/docs/app/api-reference/functions/next-root-params), only the ones it actually reads become part of its cache key.
### Cache output
A cached function produces the same output for the same inputs. The first call with a given set of inputs runs the function body and stores its output. Every later call with the same inputs reuses that output, within a render pass and across requests, for as long as the entry lasts.
Outputs are stored by a [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers), [in memory](#runtime-caching-considerations) by default, and last until they [revalidate](#revalidation).
```tsx filename="lib/orders.ts"
import { cacheLife } from 'next/cache'
export async function getOrderSummary(accountId: string) {
'use cache'
cacheLife('hours')
const orders = await getOrders(accountId)
const totals = await getOrderTotals(accountId)
return { orders, totals }
}
export async function getOrders(accountId: string) {
'use cache'
cacheLife('hours')
return db.orders.findMany({ where: { accountId } })
}
export async function getOrderTotals(accountId: string) {
return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } })
}
```
In the example above, each `accountId` has its own entry for `getOrderSummary`, holding the serialized `{ orders, totals }` object it returns. Calls to `getOrders` have their own entries, keyed by the same `accountId`. If an earlier call, through the summary or directly, already filled one, `db.orders.findMany` doesn't run and those orders become part of the summary's output. See [nested caching behavior](/docs/app/api-reference/functions/cacheLife#nested-caching-behavior) for how an inner lifetime affects the entry around it.
Note that `getOrderTotals` is not cached. It is exported so other parts of the application can read fresh totals in an uncached scope. Inside `getOrderSummary`, though, the totals query only runs when that function runs following the `'hours'` lifetime set there.
With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), prerendering fills the entry and keeps rendering, so this output contributes to the route's [static shell](/docs/app/getting-started/caching#prerendering) and can contribute to its [prefetch](/docs/app/getting-started/caching#prefetching). A cache life too short to store safely leaves a hole that resolves at request time instead. See [prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for the thresholds.
## Serialization ## Serialization
Arguments to cached functions and their return values must be serializable. Arguments to cached functions and their return values must be serializable.
...@@ -201,10 +246,10 @@ While `use cache` is designed primarily to include uncached data in the static s ...@@ -201,10 +246,10 @@ While `use cache` is designed primarily to include uncached data in the static s
With the default in-memory handler, runtime cache behavior depends on your hosting environment: With the default in-memory handler, runtime cache behavior depends on your hosting environment:
| Environment | Runtime Caching Behavior | | Environment | Runtime Caching Behavior |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Serverless** | Cache entries typically don't persist across requests (each request can be a different instance), or during revalidation. Build-time caching works normally. | | **Serverless** | Cache entries typically don't persist across requests (each request can be a different instance), or during revalidation. Build-time caching works normally. |
| **Self-hosted** | Cache entries persist across requests. Control cache size with [`cacheMaxMemorySize`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath). | | **Self-hosted** | Cache entries persist across requests. Control cache size with [`cacheMaxMemorySize`](/docs/app/api-reference/config/next-config-js/cacheMaxMemorySize). |
For example, in a serverless environment, a cached function shared by two pages executes on each static shell revalidation, whereas in self-hosted or environments with persistent memory, the cached output is reused if it's still fresh. For example, in a serverless environment, a cached function shared by two pages executes on each static shell revalidation, whereas in self-hosted or environments with persistent memory, the cached output is reused if it's still fresh.
...@@ -296,7 +341,8 @@ import { cacheLife } from 'next/cache' ...@@ -296,7 +341,8 @@ import { cacheLife } from 'next/cache'
async function getData() { async function getData() {
'use cache' 'use cache'
cacheLife('hours') // Use built-in 'hours' profile cacheLife('hours') // Use built-in 'hours' profile
return fetch('/api/data') const res = await fetch('https://api.example.com/data')
return res.json()
} }
``` ```
...@@ -310,7 +356,8 @@ If you omit `cacheLife`, the `default` profile applies and the lifetime is no lo ...@@ -310,7 +356,8 @@ If you omit `cacheLife`, the `default` profile applies and the lifetime is no lo
async function getData() { async function getData() {
'use cache' 'use cache'
// Implicitly uses the 'default' profile // Implicitly uses the 'default' profile
return fetch('/api/data') const res = await fetch('https://api.example.com/data')
return res.json()
} }
``` ```
...@@ -326,7 +373,8 @@ import { cacheTag } from 'next/cache' ...@@ -326,7 +373,8 @@ import { cacheTag } from 'next/cache'
async function getProducts() { async function getProducts() {
'use cache' 'use cache'
cacheTag('products') cacheTag('products')
return fetch('/api/products') const res = await fetch('https://api.example.com/products')
return res.json()
} }
``` ```
...@@ -345,66 +393,30 @@ Both `cacheLife` and `cacheTag` integrate across client and server caching layer ...@@ -345,66 +393,30 @@ Both `cacheLife` and `cacheTag` integrate across client and server caching layer
## Examples ## Examples
### Caching an entire route with `use cache` ### Caching function output with `use cache`
To prerender an entire route, add `use cache` to the top of **both** the `layout` and `page` files. Each of these segments are treated as separate entry points in your application, and will be cached independently.
```tsx filename="app/layout.tsx" switcher
'use cache'
export default async function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
```
```jsx filename="app/layout.js" switcher
'use cache'
export default async function Layout({ children }) {
return <div>{children}</div>
}
```
Any components imported and nested in `page` file are part of the cache output associated with the `page`.
```tsx filename="app/page.tsx" switcher You can add `use cache` to any asynchronous function, not only to components and routes. You might want to cache a network request, a database query, or a slow computation.
'use cache'
async function Users() { ```tsx filename="app/actions.ts" highlight={2} switcher
const users = await fetch('/api/users') export async function getData() {
// loop through users 'use cache'
}
export default async function Page() { const res = await fetch('https://api.example.com/data')
return ( const data = await res.json()
<main> return data
<Users />
</main>
)
} }
``` ```
```jsx filename="app/page.js" switcher ```jsx filename="app/actions.js" highlight={2} switcher
'use cache' export async function getData() {
'use cache'
async function Users() {
const users = await fetch('/api/users')
// loop through users
}
export default async function Page() { const res = await fetch('https://api.example.com/data')
return ( const data = await res.json()
<main> return data
<Users />
</main>
)
} }
``` ```
> **Good to know**:
>
> - If `use cache` is added only to the `layout` or the `page`, only that route segment and any components imported into it will be cached.
### Caching a component's output with `use cache` ### Caching a component's output with `use cache`
You can use `use cache` at the component level to cache any fetches or computations performed within that component. The cache entry will be reused as long as the serialized props produce the same value in each instance. You can use `use cache` at the component level to cache any fetches or computations performed within that component. The cache entry will be reused as long as the serialized props produce the same value in each instance.
...@@ -413,7 +425,10 @@ You can use `use cache` at the component level to cache any fetches or computati ...@@ -413,7 +425,10 @@ You can use `use cache` at the component level to cache any fetches or computati
export async function Bookings({ type = 'haircut' }: BookingsProps) { export async function Bookings({ type = 'haircut' }: BookingsProps) {
'use cache' 'use cache'
async function getBookingsData() { async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data return data
} }
return //... return //...
...@@ -428,37 +443,16 @@ interface BookingsProps { ...@@ -428,37 +443,16 @@ interface BookingsProps {
export async function Bookings({ type = 'haircut' }) { export async function Bookings({ type = 'haircut' }) {
'use cache' 'use cache'
async function getBookingsData() { async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data return data
} }
return //... return //...
} }
``` ```
### Caching function output with `use cache`
Since you can add `use cache` to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request, a database query, or a slow computation.
```tsx filename="app/actions.ts" highlight={2} switcher
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}
```
```jsx filename="app/actions.js" highlight={2} switcher
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}
```
> **Good to know:** When a cached directive (`use cache`, [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), or [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote)) is at the top of a file, you can import its exported functions into a Client Component and call them directly; they run on the server and return the result, similar to a [Server Function](/docs/app/glossary#server-function). Prefer calling cached functions on the server and passing results down as props.
### Interleaving ### Interleaving
In React, composition with `children` or slots is a well-known pattern for building flexible components. When using `use cache`, you can continue to compose your UI in this way. Anything included as `children`, or other compositional slots, in the returned JSX will be passed through the cached component without affecting its cache entry. In React, composition with `children` or slots is a well-known pattern for building flexible components. When using `use cache`, you can continue to compose your UI in this way. Anything included as `children`, or other compositional slots, in the returned JSX will be passed through the cached component without affecting its cache entry.
...@@ -485,7 +479,8 @@ async function CacheComponent({ ...@@ -485,7 +479,8 @@ async function CacheComponent({
children: ReactNode children: ReactNode
}) { }) {
'use cache' 'use cache'
const cachedData = await fetch('/api/cached-data') const res = await fetch('https://api.example.com/cached-data')
const cachedData = await res.json()
return ( return (
<div> <div>
{header} {header}
...@@ -513,7 +508,8 @@ async function CacheComponent({ ...@@ -513,7 +508,8 @@ async function CacheComponent({
children, // children: another slot for nested composition children, // children: another slot for nested composition
}) { }) {
'use cache' 'use cache'
const cachedData = await fetch('/api/cached-data') const res = await fetch('https://api.example.com/cached-data')
const cachedData = await res.json()
return ( return (
<div> <div>
{header} {header}
...@@ -590,6 +586,86 @@ export default function ClientComponent({ action }) { ...@@ -590,6 +586,86 @@ export default function ClientComponent({ action }) {
} }
``` ```
### Caching a module's exports with `use cache`
Placing the directive at the top of a file covers every export, instead of repeating it on each one. Every exported function it covers must be async.
```tsx filename="app/lib/reports.ts"
'use cache'
export async function getMonthlyTotals(accountId: string) {
return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } })
}
export async function getTopProducts() {
return db.products.findMany({ orderBy: { sales: 'desc' }, take: 10 })
}
```
Framework function exports are covered like any other, so [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) and [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must be async in such a file.
> **Good to know**:
>
> - When a cached directive (`use cache`, [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), or [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote)) is at the top of a file, you can import its exported functions into a Client Component and call them directly; they run on the server and return the result, similar to a [Server Function](/docs/app/glossary#server-function). Prefer calling cached functions on the server and passing results down as props.
### Caching a route segment's output with `use cache`
A `page` or `layout` file is a module too, so a file-level directive there follows the same rules. Each route segment is a separate entry point and is cached independently. To prerender a whole route, add `use cache` to the top of every segment file it renders: the `page`, the `layout`, and any [parallel route](/docs/app/api-reference/file-conventions/parallel-routes) slots.
```tsx filename="app/layout.tsx" switcher
'use cache'
export default async function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
```
```jsx filename="app/layout.js" switcher
'use cache'
export default async function Layout({ children }) {
return <div>{children}</div>
}
```
A cached `layout` does not cache the `children` it renders, since slots pass through without affecting its entry. See [Interleaving](#interleaving).
```tsx filename="app/page.tsx" switcher
'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// loop through users
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}
```
```jsx filename="app/page.js" switcher
'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// loop through users
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}
```
## Troubleshooting ## Troubleshooting
### Debugging cache behavior ### Debugging cache behavior
......
...@@ -7,7 +7,7 @@ The `'use client'` directive declares an entry point for the components to be re ...@@ -7,7 +7,7 @@ The `'use client'` directive declares an entry point for the components to be re
> **Good to know:** > **Good to know:**
> >
> You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the client-server [boundary](https://nextjs.org/docs/app/building-your-application/rendering#network-boundary), and the components exported from such a file serve as entry points to the client. > You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the [server and client boundary](/docs/app/guides/server-and-client-boundary), and the components exported from such a file serve as entry points to the client.
## Usage ## Usage
......
...@@ -109,36 +109,38 @@ export default function MyButton() { ...@@ -109,36 +109,38 @@ export default function MyButton() {
In the following example, `use server` is used inline at the top of a function to mark it as a [Server Function](https://19.react.dev/reference/rsc/server-functions): In the following example, `use server` is used inline at the top of a function to mark it as a [Server Function](https://19.react.dev/reference/rsc/server-functions):
```tsx filename="app/posts/[id]/page.tsx" switcher highlight={8} ```tsx filename="app/posts/[id]/page.tsx" switcher highlight={9}
import { EditPost } from './edit-post' import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export default async function PostPage({ params }: { params: { id: string } }) { export default async function PostPage({ params }: PageProps<'/posts/[id]'>) {
const post = await getPost(params.id) const { id } = await params
const post = await getPost(id)
async function updatePost(formData: FormData) { async function updatePost(formData: FormData) {
'use server' 'use server'
// Verify auth before saving (e.g. inside savePost) // Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData) await savePost(id, formData)
revalidatePath(`/posts/${params.id}`) revalidatePath(`/posts/${id}`)
} }
return <EditPost updatePostAction={updatePost} post={post} /> return <EditPost updatePostAction={updatePost} post={post} />
} }
``` ```
```jsx filename="app/posts/[id]/page.js" switcher highlight={8} ```jsx filename="app/posts/[id]/page.js" switcher highlight={9}
import { EditPost } from './edit-post' import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export default async function PostPage({ params }) { export default async function PostPage({ params }) {
const post = await getPost(params.id) const { id } = await params
const post = await getPost(id)
async function updatePost(formData) { async function updatePost(formData) {
'use server' 'use server'
// Verify auth before saving (e.g. inside savePost) // Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData) await savePost(id, formData)
revalidatePath(`/posts/${params.id}`) revalidatePath(`/posts/${id}`)
} }
return <EditPost updatePostAction={updatePost} post={post} /> return <EditPost updatePostAction={updatePost} post={post} />
......
...@@ -285,7 +285,7 @@ export default function Page() { ...@@ -285,7 +285,7 @@ export default function Page() {
} }
``` ```
```jsx filename="/app/ui/search-button.js" switcher ```jsx filename="/app/page.js" switcher
import Form from 'next/form' import Form from 'next/form'
import { SearchButton } from '@/ui/search-button' import { SearchButton } from '@/ui/search-button'
......
...@@ -239,7 +239,7 @@ An integer between `1` and `100` that sets the quality of the optimized image. H ...@@ -239,7 +239,7 @@ An integer between `1` and `100` that sets the quality of the optimized image. H
<Image quality={75} /> <Image quality={75} />
``` ```
If you’ve configured [qualities](#qualities) in `next.config.js`, the value must match one of the allowed entries. If you’ve configured [qualities](#qualities) in `next.config.js`, a value outside that list is coerced to the closest allowed entry. For example, with `qualities: [50, 75, 100]`, a `quality` of `80` is served as `75`. Development logs a warning so you can add the value to the allowlist.
> **Good to know**: If the original image is already low quality, setting a high quality value will increase the file size without improving appearance. > **Good to know**: If the original image is already low quality, setting a high quality value will increase the file size without improving appearance.
...@@ -1069,7 +1069,7 @@ export default function MyImage() { ...@@ -1069,7 +1069,7 @@ export default function MyImage() {
} }
``` ```
When using `fill`, the parent element must have `position: relative` or `display: block`. This is necessary for the proper rendering of the image element in that layout mode. When using `fill`, the parent element must be positioned, with `position: relative`, `fixed`, or `absolute`. The image itself uses `position: absolute`, so it sizes against the nearest positioned ancestor.
```jsx ```jsx
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
......
...@@ -70,14 +70,14 @@ The following props can be passed to the `<Link>` component: ...@@ -70,14 +70,14 @@ The following props can be passed to the `<Link>` component:
<AppOnly> <AppOnly>
| Prop | Example | Type | Required | | Prop | Example | Type | Required |
| ------------------------------------- | -------------------------------- | ---------------- | -------- | | ------------------------------------- | -------------------------------- | -------------------------- | -------- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes | | [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes |
| [`replace`](#replace) | `replace={false}` | Boolean | - | | [`replace`](#replace) | `replace={false}` | Boolean | - |
| [`scroll`](#scroll) | `scroll={false}` | Boolean | - | | [`scroll`](#scroll) | `scroll={false}` | Boolean | - |
| [`prefetch`](#prefetch) | `prefetch={false}` | Boolean or null | - | | [`prefetch`](#prefetch) | `prefetch={false}` | Boolean, `"auto"`, or null | - |
| [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - | | [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - |
| [`transitionTypes`](#transitiontypes) | `transitionTypes={['slide-in']}` | `string[]` | - | | [`transitionTypes`](#transitiontypes) | `transitionTypes={['slide-in']}` | `string[]` | - |
</AppOnly> </AppOnly>
...@@ -300,7 +300,7 @@ Prefetching happens when a `<Link />` component enters the user's viewport (init ...@@ -300,7 +300,7 @@ Prefetching happens when a `<Link />` component enters the user's viewport (init
The following values can be passed to the `prefetch` prop: The following values can be passed to the `prefetch` prop:
- **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched. - **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched.
- **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch is the [App Shell](/docs/app/glossary#app-shell) plus the per-link runtime data and the cached content behind it. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). - **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch includes the [App Shell](/docs/app/glossary#app-shell) and cached content that depends on the link's URL data. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
- `false`: Prefetching will never happen both on entering the viewport and on hover. - `false`: Prefetching will never happen both on entering the viewport and on hover.
> **With Partial Prefetching enabled** ([`partialPrefetching: true`](/docs/app/api-reference/config/next-config-js/partialPrefetching)): the default changes. `auto` prefetches the per-route [App Shell](/docs/app/glossary#app-shell) (the route's static and cached content) instead of the full page. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full behavior change. > **With Partial Prefetching enabled** ([`partialPrefetching: true`](/docs/app/api-reference/config/next-config-js/partialPrefetching)): the default changes. `auto` prefetches the per-route [App Shell](/docs/app/glossary#app-shell) (the route's static and cached content) instead of the full page. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full behavior change.
...@@ -333,7 +333,7 @@ export default function Page() { ...@@ -333,7 +333,7 @@ export default function Page() {
<PagesOnly> <PagesOnly>
Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation's. **Prefetching is only enabled in production**. Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation. **Prefetching is only enabled in production**.
The following values can be passed to the `prefetch` prop: The following values can be passed to the `prefetch` prop:
......
...@@ -72,7 +72,7 @@ Scripts denoted with this strategy are preloaded and fetched before any first-pa ...@@ -72,7 +72,7 @@ Scripts denoted with this strategy are preloaded and fetched before any first-pa
<AppOnly> <AppOnly>
`beforeInteractive` scripts must be placed inside the root layout (`app/layout.tsx`) and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side). Scripts with the `beforeInteractive` strategy must be placed inside a [root layout](/docs/app/api-reference/file-conventions/layout#root-layout), such as `app/layout.tsx` or `app/[locale]/layout.tsx`, and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
</AppOnly> </AppOnly>
...@@ -155,6 +155,12 @@ export default function Document() { ...@@ -155,6 +155,12 @@ export default function Document() {
> **Good to know**: Scripts with `beforeInteractive` will always be injected inside the `head` of the HTML document regardless of where it's placed in the component. > **Good to know**: Scripts with `beforeInteractive` will always be injected inside the `head` of the HTML document regardless of where it's placed in the component.
<AppOnly>
> **Good to know**: These scripts run once per document load. A client-side navigation does not run them again, including one that only changes a root param, such as `/en` to `/fi`, since the root layout stays the same.
</AppOnly>
Some examples of scripts that should be fetched as soon as possible with `beforeInteractive` include: Some examples of scripts that should be fetched as soon as possible with `beforeInteractive` include:
- Bot detectors - Bot detectors
......
...@@ -389,7 +389,7 @@ export default async function sitemap(props) { ...@@ -389,7 +389,7 @@ export default async function sitemap(props) {
} }
``` ```
Your generated sitemaps will be available at `/.../sitemap/[id]`. For example, `/product/sitemap/1.xml`. Your generated sitemaps will be available at `/.../sitemap/[id].xml`. For example, `/product/sitemap/1.xml`.
See the [`generateSitemaps` API reference](/docs/app/api-reference/functions/generate-sitemaps) for more information. See the [`generateSitemaps` API reference](/docs/app/api-reference/functions/generate-sitemaps) for more information.
...@@ -413,6 +413,8 @@ type Sitemap = Array<{ ...@@ -413,6 +413,8 @@ type Sitemap = Array<{
alternates?: { alternates?: {
languages?: Languages<string> languages?: Languages<string>
} }
images?: string[]
videos?: Videos[]
}> }>
``` ```
......
...@@ -39,11 +39,11 @@ export default function Page() { ...@@ -39,11 +39,11 @@ export default function Page() {
Opts the segment into [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) without enabling the global [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag. A `<Link>` pointing at a segment with `prefetch = 'partial'` loads the per-route [App Shell](/docs/app/glossary#app-shell) instead of the legacy full prefetch. Set this on the destination, not the link. Opts the segment into [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) without enabling the global [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag. A `<Link>` pointing at a segment with `prefetch = 'partial'` loads the per-route [App Shell](/docs/app/glossary#app-shell) instead of the legacy full prefetch. Set this on the destination, not the link.
For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js may also prefetch the segment at runtime. The server renders a fresh response that resolves per-link runtime data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime. For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js uses per-link prefetching. The server renders a fresh response that resolves URL data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime.
Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports. Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports.
> **Good to know**: When Next.js runtime-prefetches a segment, all downstream segments are included in the same runtime prefetch request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the runtime response. > **Good to know**: When Next.js performs a per-link prefetch for a segment, all downstream segments are included in the same request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the response.
```tsx filename="page.tsx" ```tsx filename="page.tsx"
export const prefetch = 'partial' export const prefetch = 'partial'
...@@ -61,7 +61,7 @@ A prefetch starts with a `<Link>` that expresses intent (should this destination ...@@ -61,7 +61,7 @@ A prefetch starts with a `<Link>` that expresses intent (should this destination
A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls: A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls:
- [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves per-link runtime data (`params`, `searchParams`, the full URL). - [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves URL data (`params`, `searchParams`, and the full URL) and the cached content behind it.
- [`'force-disabled'`](#force-disabled): skip segment data entirely. - [`'force-disabled'`](#force-disabled): skip segment data entirely.
`<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured. `<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured.
......
...@@ -108,7 +108,7 @@ By default, Next.js keeps track of the active _state_ (or subpage) for each slot ...@@ -108,7 +108,7 @@ By default, Next.js keeps track of the active _state_ (or subpage) for each slot
### With `useSelectedLayoutSegment(s)` ### With `useSelectedLayoutSegment(s)`
Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRoutesKey` parameter, which allows you to read the active route segment within a slot. Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRouteKey` parameter, which allows you to read the active route segment within a slot.
```tsx filename="app/layout.tsx" switcher ```tsx filename="app/layout.tsx" switcher
'use client' 'use client'
......
...@@ -138,9 +138,11 @@ Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp ...@@ -138,9 +138,11 @@ Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp
## Params ## Params
Next.js calls the Proxy function with two arguments, [`request`](#request) and [`event`](#event), in that order. Declare only the ones you use.
### `request` ### `request`
When defining Proxy, the default export function accepts a single parameter, `request`. This parameter is an instance of `NextRequest`, which represents the incoming HTTP request. The first parameter is an instance of `NextRequest`, which represents the incoming HTTP request.
```tsx filename="proxy.ts" switcher ```tsx filename="proxy.ts" switcher
import type { NextRequest } from 'next/server' import type { NextRequest } from 'next/server'
...@@ -156,6 +158,36 @@ export function proxy(request) { ...@@ -156,6 +158,36 @@ export function proxy(request) {
} }
``` ```
### `event`
The second parameter is an instance of `NextFetchEvent`. It exposes a single method, `waitUntil(promise)`, which keeps the Proxy invocation alive until the promise settles, so background work like logging or analytics can finish after the response is sent. See [`waitUntil` and `NextFetchEvent`](#waituntil-and-nextfetchevent) for a full example.
```tsx filename="proxy.ts" switcher
import type { NextFetchEvent, NextRequest } from 'next/server'
export function proxy(request: NextRequest, event: NextFetchEvent) {
event.waitUntil(
fetch('https://example.com/log', {
method: 'POST',
body: JSON.stringify({ pathname: request.nextUrl.pathname }),
})
)
}
```
```js filename="proxy.js" switcher
export function proxy(request, event) {
event.waitUntil(
fetch('https://example.com/log', {
method: 'POST',
body: JSON.stringify({ pathname: request.nextUrl.pathname }),
})
)
}
```
### `NextProxy` type
If you prefer a shorthand, you can use the `NextProxy` type. It infers the parameter types for both `request` (`NextRequest`) and `event` (`NextFetchEvent`) automatically: If you prefer a shorthand, you can use the `NextProxy` type. It infers the parameter types for both `request` (`NextRequest`) and `event` (`NextFetchEvent`) automatically:
```tsx filename="proxy.ts" ```tsx filename="proxy.ts"
......
...@@ -34,7 +34,7 @@ const nextConfig = { ...@@ -34,7 +34,7 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
} }
export default nextConfig module.exports = nextConfig
``` ```
`cacheLife` can only be used within a cache directive scope. `cacheLife` can only be used within a cache directive scope.
...@@ -265,7 +265,7 @@ A short cache lifetime changes where the cached content can be delivered from: ...@@ -265,7 +265,7 @@ A short cache lifetime changes where the cached content can be delivered from:
- **`revalidate` of `0`, or `expire` under 5 minutes**: excluded from prerenders, becoming a "dynamic hole" resolved at request time. - **`revalidate` of `0`, or `expire` under 5 minutes**: excluded from prerenders, becoming a "dynamic hole" resolved at request time.
- **`stale` under 30 seconds**: excluded from prerenders, because a prefetch would expire before the user could click. - **`stale` under 30 seconds**: excluded from prerenders, because a prefetch would expire before the user could click.
- **`stale` from 30 seconds up to 5 minutes**: included in prerenders, but excluded from the route's [App Shell](/docs/app/glossary#app-shell). - **`stale` of at least 30 seconds but under 5 minutes**: included in prerenders, but excluded from the route's [App Shell](/docs/app/glossary#app-shell).
Of the presets, only `seconds` falls under any of these thresholds: its `expire` of 1 minute excludes it from prerenders. Of the presets, only `seconds` falls under any of these thresholds: its `expire` of 1 minute excludes it from prerenders.
......
...@@ -33,7 +33,7 @@ const nextConfig = { ...@@ -33,7 +33,7 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
} }
export default nextConfig module.exports = nextConfig
``` ```
The `cacheTag` function takes one or more string values. The `cacheTag` function takes one or more string values.
...@@ -44,7 +44,8 @@ import { cacheTag } from 'next/cache' ...@@ -44,7 +44,8 @@ import { cacheTag } from 'next/cache'
export async function getData() { export async function getData() {
'use cache' 'use cache'
cacheTag('my-data') cacheTag('my-data')
const data = await fetch('/api/data') const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data return data
} }
``` ```
...@@ -55,7 +56,8 @@ import { cacheTag } from 'next/cache' ...@@ -55,7 +56,8 @@ import { cacheTag } from 'next/cache'
export async function getData() { export async function getData() {
'use cache' 'use cache'
cacheTag('my-data') cacheTag('my-data')
const data = await fetch('/api/data') const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data return data
} }
``` ```
...@@ -118,7 +120,10 @@ export async function Bookings({ type = 'haircut' }: BookingsProps) { ...@@ -118,7 +120,10 @@ export async function Bookings({ type = 'haircut' }: BookingsProps) {
cacheTag('bookings-data') cacheTag('bookings-data')
async function getBookingsData() { async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data return data
} }
...@@ -134,7 +139,10 @@ export async function Bookings({ type = 'haircut' }) { ...@@ -134,7 +139,10 @@ export async function Bookings({ type = 'haircut' }) {
cacheTag('bookings-data') cacheTag('bookings-data')
async function getBookingsData() { async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data return data
} }
...@@ -156,7 +164,10 @@ interface BookingsProps { ...@@ -156,7 +164,10 @@ interface BookingsProps {
export async function Bookings({ type = 'haircut' }: BookingsProps) { export async function Bookings({ type = 'haircut' }: BookingsProps) {
async function getBookingsData() { async function getBookingsData() {
'use cache' 'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
cacheTag('bookings-data', data.id) cacheTag('bookings-data', data.id)
return data return data
} }
...@@ -170,7 +181,10 @@ import { cacheTag } from 'next/cache' ...@@ -170,7 +181,10 @@ import { cacheTag } from 'next/cache'
export async function Bookings({ type = 'haircut' }) { export async function Bookings({ type = 'haircut' }) {
async function getBookingsData() { async function getBookingsData() {
'use cache' 'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
cacheTag('bookings-data', data.id) cacheTag('bookings-data', data.id)
return data return data
} }
......
...@@ -8,6 +8,8 @@ related: ...@@ -8,6 +8,8 @@ related:
- app/api-reference/file-conventions/error - app/api-reference/file-conventions/error
--- ---
<AppOnly>
The `catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to the [`error.js`](/docs/app/api-reference/file-conventions/error) file convention, enabling component-level error recovery anywhere in your component tree. The `catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to the [`error.js`](/docs/app/api-reference/file-conventions/error) file convention, enabling component-level error recovery anywhere in your component tree.
Compared to a custom React error boundary, `catchError` is designed to work with Next.js out of the box: Compared to a custom React error boundary, `catchError` is designed to work with Next.js out of the box:
...@@ -54,6 +56,51 @@ function ErrorFallback(props, { error, retry }) { ...@@ -54,6 +56,51 @@ function ErrorFallback(props, { error, retry }) {
export default catchError(ErrorFallback) export default catchError(ErrorFallback)
``` ```
</AppOnly>
<PagesOnly>
The `catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to writing a [custom React error boundary class](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary), enabling component-level error recovery anywhere in your component tree.
Compared to a custom React error boundary, `catchError` is designed to work with Next.js out of the box:
- **Built-in error recovery** — `reset()` re-renders the error boundary's children, letting users recover from errors without a full page reload.
- **Client navigation handling** — The error state automatically clears when you do a client navigation to a different route.
```tsx filename="components/custom-error-boundary.tsx" switcher
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, reset }: ErrorInfo) {
return (
<div>
<h2>{props.title}</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
```jsx filename="components/custom-error-boundary.js" switcher
import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) {
return (
<div>
<h2>{props.title}</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
</PagesOnly>
## Reference ## Reference
### Parameters ### Parameters
...@@ -71,6 +118,8 @@ A function that renders the error UI when an error is caught. It receives two ar ...@@ -71,6 +118,8 @@ A function that renders the error UI when an error is caught. It receives two ar
- `props` — The props passed to the wrapper component (excluding `children`). - `props` — The props passed to the wrapper component (excluding `children`).
- `errorInfo` — An object containing information about the error: - `errorInfo` — An object containing information about the error:
<AppOnly>
| Property | Type | Description | | Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | -------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. | | `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. |
...@@ -79,6 +128,17 @@ A function that renders the error UI when an error is caught. It receives two ar ...@@ -79,6 +128,17 @@ A function that renders the error UI when an error is caught. It receives two ar
The `fallback` function must be a Client Component (or defined in a `'use client'` module). The `fallback` function must be a Client Component (or defined in a `'use client'` module).
</AppOnly>
<PagesOnly>
| Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. |
| `reset` | `() => void` | Resets the error state and re-renders the error boundary's children. |
</PagesOnly>
### Returns ### Returns
`catchError` returns a React component that: `catchError` returns a React component that:
...@@ -89,10 +149,12 @@ The `fallback` function must be a Client Component (or defined in a `'use client ...@@ -89,10 +149,12 @@ The `fallback` function must be a Client Component (or defined in a `'use client
## Examples ## Examples
### Client Component ### Basic usage
Define a fallback and use the returned component to wrap parts of your UI: Define a fallback and use the returned component to wrap parts of your UI:
<AppOnly>
```tsx filename="app/some-component.tsx" switcher ```tsx filename="app/some-component.tsx" switcher
import ErrorWrapper from '../custom-error-boundary' import ErrorWrapper from '../custom-error-boundary'
...@@ -109,8 +171,32 @@ export default function Component({ children }) { ...@@ -109,8 +171,32 @@ export default function Component({ children }) {
} }
``` ```
</AppOnly>
<PagesOnly>
```tsx filename="components/some-component.tsx" switcher
import ErrorWrapper from './custom-error-boundary'
export default function Component({ children }: { children: React.ReactNode }) {
return <ErrorWrapper title="Dashboard Error">{children}</ErrorWrapper>
}
```
```jsx filename="components/some-component.js" switcher
import ErrorWrapper from './custom-error-boundary'
export default function Component({ children }) {
return <ErrorWrapper title="Dashboard Error">{children}</ErrorWrapper>
}
```
</PagesOnly>
### Recovering from errors ### Recovering from errors
<AppOnly>
Use `retry()` to prompt the user to recover from the error. When called, the function re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result. Use `retry()` to prompt the user to recover from the error. When called, the function re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result.
In most cases, use `retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors. In most cases, use `retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors.
...@@ -151,6 +237,46 @@ function ErrorFallback(props, { error, retry, reset }) { ...@@ -151,6 +237,46 @@ function ErrorFallback(props, { error, retry, reset }) {
export default catchError(ErrorFallback) export default catchError(ErrorFallback)
``` ```
</AppOnly>
<PagesOnly>
Use `reset()` to prompt the user to recover from the error. When called, the function clears the error state and re-renders the error boundary's children.
```tsx filename="components/custom-error-boundary.tsx" switcher
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: {}, { error, reset }: ErrorInfo) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
```jsx filename="components/custom-error-boundary.js" switcher
import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
</PagesOnly>
<AppOnly>
### Server-rendered error fallback ### Server-rendered error fallback
You can pass server-rendered content as a prop to display data-driven fallback UI. This works by rendering a Server Component as a `React.ReactNode` prop that the fallback displays when an error is caught. You can pass server-rendered content as a prop to display data-driven fallback UI. This works by rendering a Server Component as a `React.ReactNode` prop that the fallback displays when an error is caught.
...@@ -216,6 +342,14 @@ export default function Component({ children }) { ...@@ -216,6 +342,14 @@ export default function Component({ children }) {
> - Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations. > - Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations.
> - You don't need to wrap `error.js` default exports with `catchError`. The [`error.js`](/docs/app/api-reference/file-conventions/error) file convention already renders inside a built-in error boundary provided by Next.js. > - You don't need to wrap `error.js` default exports with `catchError`. The [`error.js`](/docs/app/api-reference/file-conventions/error) file convention already renders inside a built-in error boundary provided by Next.js.
</AppOnly>
<PagesOnly>
> **Good to know**: Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations.
</PagesOnly>
## Version History ## Version History
| Version | Changes | | Version | Changes |
......
...@@ -98,7 +98,7 @@ fetch(url, { signal }) ...@@ -98,7 +98,7 @@ fetch(url, { signal })
## Troubleshooting ## Troubleshooting
### Fetch default `auto no store` and `cache: 'no-store'` not showing fresh data in development ### Fetch default `auto no cache` and `cache: 'no-store'` not showing fresh data in development
Next.js caches `fetch` responses in Server Components across Hot Module Replacement (HMR) in local development for faster responses and to reduce costs for billed API calls. Next.js caches `fetch` responses in Server Components across Hot Module Replacement (HMR) in local development for faster responses and to reduce costs for billed API calls.
......
...@@ -383,7 +383,6 @@ export const metadata = { ...@@ -383,7 +383,6 @@ export const metadata = {
<meta name="generator" content="Next.js" /> <meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" /> <meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" /> <meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" /> <meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" /> <meta name="publisher" content="Sebastian Markbåge" />
<meta name="format-detection" content="telephone=no, address=no, email=no" /> <meta name="format-detection" content="telephone=no, address=no, email=no" />
...@@ -422,6 +421,7 @@ export const metadata = { ...@@ -422,6 +421,7 @@ export const metadata = {
> **Good to know**: > **Good to know**:
> >
> - `metadataBase` is typically set in root `app/layout.js` to apply to URL-based `metadata` fields across all routes. > - `metadataBase` is typically set in root `app/layout.js` to apply to URL-based `metadata` fields across all routes.
> - When `generateMetadata` uses `'use cache'`, its return value must be serializable. `URL` instances are not supported by Cache Functions, so values such as `metadataBase` should be returned as strings (for example, `url.toString()`). See [`use cache` serialization requirements](/docs/app/api-reference/directives/use-cache#serialization).
> - All URL-based `metadata` fields that require absolute URLs can be configured with a `metadataBase` option. > - All URL-based `metadata` fields that require absolute URLs can be configured with a `metadataBase` option.
> - `metadataBase` can contain a subdomain e.g. `https://app.acme.com` or base path e.g. `https://acme.com/start/from/here` > - `metadataBase` can contain a subdomain e.g. `https://app.acme.com` or base path e.g. `https://acme.com/start/from/here`
> - If a `metadata` field provides an absolute URL, `metadataBase` will be ignored. > - If a `metadata` field provides an absolute URL, `metadataBase` will be ignored.
...@@ -924,6 +924,24 @@ export const metadata = { ...@@ -924,6 +924,24 @@ export const metadata = {
<link rel="bookmarks" href="https://nextjs.org/13" /> <link rel="bookmarks" href="https://nextjs.org/13" />
``` ```
### `pagination`
Describes the previous and next pages in a paginated sequence.
```jsx filename="layout.js | page.js"
export const metadata = {
pagination: {
previous: 'https://nextjs.org/blog?page=1',
next: 'https://nextjs.org/blog?page=3',
},
}
```
```html filename="<head> output" hideLineNumbers
<link rel="prev" href="https://nextjs.org/blog?page=1" />
<link rel="next" href="https://nextjs.org/blog?page=3" />
```
### `category` ### `category`
```jsx filename="layout.js | page.js" ```jsx filename="layout.js | page.js"
...@@ -1124,7 +1142,7 @@ The following metadata types do not currently have built-in support. However, th ...@@ -1124,7 +1142,7 @@ The following metadata types do not currently have built-in support. However, th
| `<style>` | Learn more about [styling in Next.js](/docs/app/getting-started/css). | | `<style>` | Learn more about [styling in Next.js](/docs/app/getting-started/css). |
| `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). | | `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). |
| `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. | | `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. |
| `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) | | `<link rel="preload" />` | Use [ReactDOM preload method](#link-relpreload) |
| `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) | | `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) |
| `<link rel="dns-prefetch" />` | Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) | | `<link rel="dns-prefetch" />` | Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) |
...@@ -1422,5 +1440,5 @@ export const metadata = { ...@@ -1422,5 +1440,5 @@ export const metadata = {
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v15.2.0` | Introduced streaming support to `generateMetadata`. | | `v15.2.0` | Introduced streaming support to `generateMetadata`. |
| `v13.2.0` | `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). | | `v14.0.0` | `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). |
| `v13.2.0` | `metadata` and `generateMetadata` introduced. | | `v13.2.0` | `metadata` and `generateMetadata` introduced. |
...@@ -54,7 +54,7 @@ export default async function Page({ params }) { ...@@ -54,7 +54,7 @@ export default async function Page({ params }) {
> **Good to know**: > **Good to know**:
> >
> - You can use the [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config/dynamicParams) segment config option to control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`. > - You can use the [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config/dynamicParams) segment config option to control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`.
> - You must return [an empty array from `generateStaticParams`](#all-paths-at-build-time) or utilize [`export const dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic) in order to revalidate (ISR) [paths at runtime](#all-paths-at-runtime). > - You must return [an empty array from `generateStaticParams`](#all-paths-at-runtime) or utilize [`export const dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic) in order to revalidate (ISR) [paths at runtime](#all-paths-at-runtime).
> - During `next dev`, `generateStaticParams` will be called when you navigate to a route. > - During `next dev`, `generateStaticParams` will be called when you navigate to a route.
> - During `next build`, `generateStaticParams` runs before the corresponding Layouts or Pages are generated. > - During `next build`, `generateStaticParams` runs before the corresponding Layouts or Pages are generated.
> - During revalidation (ISR), `generateStaticParams` will not be called again. > - During revalidation (ISR), `generateStaticParams` will not be called again.
......
...@@ -46,7 +46,7 @@ Please refer to [Satori’s documentation](https://github.com/vercel/satori#css) ...@@ -46,7 +46,7 @@ Please refer to [Satori’s documentation](https://github.com/vercel/satori#css)
## Behavior ## Behavior
- `ImageResponse` uses [@vercel/og](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG. - `ImageResponse` uses [@vercel/og](https://vercel.com/docs/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG.
- Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work. - Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work.
- Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime. - Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime.
- Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`. - Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`.
......
...@@ -12,8 +12,6 @@ When used in a streaming context, this will insert a meta tag to emit the redire ...@@ -12,8 +12,6 @@ When used in a streaming context, this will insert a meta tag to emit the redire
If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead. If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead.
> **Good to know**: If you prefer to return a 307 (Temporary) HTTP redirect instead of 308 (Permanent), you can use the [`redirect` function](/docs/app/api-reference/functions/redirect) instead.
## Parameters ## Parameters
The `permanentRedirect` function accepts two arguments: The `permanentRedirect` function accepts two arguments:
...@@ -45,6 +43,11 @@ The `type` parameter has no effect when used in Server Components. ...@@ -45,6 +43,11 @@ The `type` parameter has no effect when used in Server Components.
`permanentRedirect` does not return a value. `permanentRedirect` does not return a value.
## Behavior
- In Server Actions and Route Handlers, `permanentRedirect` should be called **outside** the `try` block when using `try/catch` statements because it throws an error.
- If you prefer to return a 307 (Temporary) HTTP redirect instead of 308 (Permanent), you can use the [`redirect` function](/docs/app/api-reference/functions/redirect) instead.
## Example ## Example
Invoking the `permanentRedirect()` function throws a `NEXT_REDIRECT` error and terminates rendering of the route segment in which it was thrown. Invoking the `permanentRedirect()` function throws a `NEXT_REDIRECT` error and terminates rendering of the route segment in which it was thrown.
......
...@@ -8,7 +8,7 @@ related: ...@@ -8,7 +8,7 @@ related:
`revalidateTag` allows you to invalidate cached data on-demand for a specific cache tag. `revalidateTag` allows you to invalidate cached data on-demand for a specific cache tag.
This function is ideal for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. Users receive stale content while fresh data loads in the background. This function is ideal for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. With the recommended `max` profile, users receive stale content while fresh data loads in the background.
## Usage ## Usage
...@@ -18,13 +18,16 @@ This function is ideal for content where a slight delay in updates is acceptable ...@@ -18,13 +18,16 @@ This function is ideal for content where a slight delay in updates is acceptable
### Revalidation Behavior ### Revalidation Behavior
The revalidation behavior depends on whether you provide the second argument: Calling `revalidateTag` marks the tagged data as stale. The next request for that data kicks off a revalidation and is served stale content while it runs, using stale-while-revalidate semantics. The second argument sets how long stale content may be served. Past that, a request blocks until the revalidation completes.
- **With `profile="max"` (recommended)**: The tag entry is marked as stale, and the next time a resource with that tag is visited, it will use stale-while-revalidate semantics. This means the stale content is served while fresh content is fetched in the background. - **`profile="max"` (recommended)**: A one year window, long enough that requests are always served stale content while the revalidation runs.
- **With a custom cache life profile**: For advanced usage, you can specify any cache life profile that your application has defined, allowing for custom revalidation behaviors tailored to your specific caching requirements. - **Another profile, or an object**: Any other default or custom profile defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife), or an object with an `expire` property, when you want a different window.
- **Without the second argument (deprecated)**: The tag entry is expired immediately, and the next request to that resource will be a blocking revalidate/cache miss. This behavior is now deprecated, and you should either use `profile="max"` or migrate to [`updateTag`](/docs/app/api-reference/functions/updateTag). - **`{ expire: 0 }`**: Stale content is never served, so the next request is a blocking revalidate/cache miss. Use it when the caller needs the data gone immediately and you cannot use [`updateTag`](/docs/app/api-reference/functions/updateTag).
- **No second argument (deprecated)**: Behaves like `{ expire: 0 }`. Migrate to [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions, or `profile="max"`.
> **Good to know**: When using `profile="max"`, `revalidateTag` marks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means calling `revalidateTag` will not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag is next visited. The profile sets the point past which data correctness is more important than being fast.
> **Good to know**: A revalidation is triggered by a request, not by the `revalidateTag` call, so pages using the tag revalidate as they are visited rather than all at once.
## Parameters ## Parameters
...@@ -32,8 +35,8 @@ The revalidation behavior depends on whether you provide the second argument: ...@@ -32,8 +35,8 @@ The revalidation behavior depends on whether you provide the second argument:
revalidateTag(tag: string, profile: string | { expire?: number }): void; revalidateTag(tag: string, profile: string | { expire?: number }): void;
``` ```
- `tag`: A string representing the cache tag associated with the data you want to revalidate. Must not exceed 256 characters. This value is case-sensitive. - `tag`: A string representing the cache tag associated with the data you want to revalidate. Tags are case-sensitive and must not exceed 256 characters. A tag that exceeds the limit is never assigned to cached data, so revalidating it does nothing.
- `profile`: A string that specifies the revalidation behavior. The recommended value is `"max"` which provides stale-while-revalidate semantics, or any of the other default or custom profiles defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife). Alternatively, you can pass an object with an `expire` property for custom expiration behavior. - `profile`: How long stale content may be served, see [Revalidation Behavior](#revalidation-behavior). The recommended value is `"max"`. Any other default or custom profile defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife) is also accepted, and only its `expire` is read. You can also pass an object with an `expire` property, in seconds.
Tags must first be assigned to cached data. You can do this in two ways: Tags must first be assigned to cached data. You can do this in two ways:
...@@ -136,4 +139,8 @@ export async function GET(request) { ...@@ -136,4 +139,8 @@ export async function GET(request) {
} }
``` ```
> **Good to know**: For webhooks or third-party services that need immediate expiration, you can pass `{ expire: 0 }` as the second argument: `revalidateTag(tag, { expire: 0 })`. This pattern is necessary when external systems call your Route Handlers and require data to expire immediately. For all other cases, it's recommended to use [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions for immediate updates instead. When the invalidation comes from outside a Server Action, for example a webhook or another service calling a Route Handler, [`updateTag`](/docs/app/api-reference/functions/updateTag) is not available. Pass `{ expire: 0 }` to expire the data immediately:
```ts
revalidateTag(tag, { expire: 0 })
```
...@@ -121,7 +121,7 @@ export async function createPost(formData) { ...@@ -121,7 +121,7 @@ export async function createPost(formData) {
### Error when used outside Server Actions ### Error when used outside Server Actions
```ts filename="app/api/posts/route.ts" switcher ```ts filename="app/api/posts/route.ts" switcher
import { updateTag } from 'next/cache' import { revalidateTag, updateTag } from 'next/cache'
export async function POST() { export async function POST() {
// This will throw an error // This will throw an error
......
...@@ -40,10 +40,10 @@ export default function ExampleClientComponent() { ...@@ -40,10 +40,10 @@ export default function ExampleClientComponent() {
## Parameters ## Parameters
```tsx ```tsx
const segment = useSelectedLayoutSegment(parallelRoutesKey?: string) const segment = useSelectedLayoutSegment(parallelRouteKey?: string)
``` ```
`useSelectedLayoutSegment` _optionally_ accepts a [`parallelRoutesKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot. `useSelectedLayoutSegment` _optionally_ accepts a [`parallelRouteKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
## Returns ## Returns
......
...@@ -52,10 +52,10 @@ export default function ExampleClientComponent() { ...@@ -52,10 +52,10 @@ export default function ExampleClientComponent() {
## Parameters ## Parameters
```tsx ```tsx
const segments = useSelectedLayoutSegments(parallelRoutesKey?: string) const segments = useSelectedLayoutSegments(parallelRouteKey?: string)
``` ```
`useSelectedLayoutSegments` _optionally_ accepts a [`parallelRoutesKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot. `useSelectedLayoutSegments` _optionally_ accepts a [`parallelRouteKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
## Returns ## Returns
......
...@@ -8,14 +8,14 @@ description: Learn how to use the assetPrefix config option to configure your CD ...@@ -8,14 +8,14 @@ description: Learn how to use the assetPrefix config option to configure your CD
<AppOnly> <AppOnly>
> **Attention**: [Deploying to Vercel](/docs/app/getting-started/deploying) automatically configures a global CDN for your Next.js project. > **Attention**: [Deploying to Vercel](/docs/app/getting-started/deploying) automatically configures a global CDN for your Next.js project.
> You do not need to manually setup an Asset Prefix. > You do not need to manually set up an Asset Prefix.
</AppOnly> </AppOnly>
<PagesOnly> <PagesOnly>
> **Attention**: [Deploying to Vercel](/docs/pages/getting-started/deploying) automatically configures a global CDN for your Next.js project. > **Attention**: [Deploying to Vercel](/docs/pages/getting-started/deploying) automatically configures a global CDN for your Next.js project.
> You do not need to manually setup an Asset Prefix. > You do not need to manually set up an Asset Prefix.
</PagesOnly> </PagesOnly>
......
...@@ -471,7 +471,7 @@ For a full explanation of the tag architecture (including soft tags and multi-in ...@@ -471,7 +471,7 @@ For a full explanation of the tag architecture (including soft tags and multi-in
## Soft Tags ## Soft Tags
Soft tags are implicit tags that Next.js automatically generates based on the route path. For example, the route `/blog/hello` generates soft tags for `/`, `/blog`, `/blog/hello`, and their corresponding layout entries. These tags are prefixed internally with `_N_T_`. Soft tags are implicit tags that Next.js automatically generates based on the route path. Every segment in the path gets a layout tag, plus the leaf route itself. For example, the route `/blog/hello` generates soft tags for `/layout`, `/blog/layout`, `/blog/hello/layout`, and `/blog/hello`. These tags are prefixed internally with `_N_T_`.
Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based cache system. When `revalidatePath('/blog/hello')` is called, it invalidates all cache entries associated with that path's soft tags. Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based cache system. When `revalidatePath('/blog/hello')` is called, it invalidates all cache entries associated with that path's soft tags.
......
...@@ -54,7 +54,8 @@ import { cacheLife } from 'next/cache' ...@@ -54,7 +54,8 @@ import { cacheLife } from 'next/cache'
export async function getCachedData() { export async function getCachedData() {
'use cache' 'use cache'
cacheLife('blog') cacheLife('blog')
const data = await fetch('/api/data') const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data return data
} }
``` ```
...@@ -65,7 +66,8 @@ import { cacheLife } from 'next/cache' ...@@ -65,7 +66,8 @@ import { cacheLife } from 'next/cache'
export async function getCachedData() { export async function getCachedData() {
'use cache' 'use cache'
cacheLife('blog') cacheLife('blog')
const data = await fetch('/api/data') const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data return data
} }
``` ```
......
---
title: cacheMaxMemorySize
description: Configure the size of the in-memory cache that Next.js keeps in each server instance.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
`cacheMaxMemorySize` sets the size, in bytes, of the in-memory cache each Next.js server instance keeps. It defaults to 50 MB.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheMaxMemorySize: 50 * 1024 * 1024, // 50 MB, the default
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheMaxMemorySize: 50 * 1024 * 1024, // 50 MB, the default
}
module.exports = nextConfig
```
The option sizes two separate caches:
- The server cache that stores prerendered pages, route handler responses, and optimized images. Set this to `0` when adopting a [custom `cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath), so reads go to your store rather than a per-instance copy.
- The built-in handler behind [`'use cache'`](/docs/app/api-reference/directives/use-cache). If you register your own handler through [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers), that handler manages its own memory and this option no longer applies to it.
Setting `cacheMaxMemorySize: 0` disables both in-memory caches. It is also a way to mimic how `use cache` behaves in a serverless environment, where entries rarely survive between requests.
> **Good to know**: `next dev` keeps its own in-memory cache regardless of this option, so reloads stay fast. Production honors the configured value exactly.
...@@ -68,12 +68,15 @@ module.exports = { ...@@ -68,12 +68,15 @@ module.exports = {
} }
``` ```
A per-deployment value only avoids skew if requests are also routed by deployment. Next.js does not route on `?dpl=`, so that routing comes from your host or CDN. Without it, clients that reach an instance from another deployment during a rollout will reload rather than navigate.
## Version History ## Version History
| Version | Changes | | Version | Changes |
| ---------- | ----------------------------------------------------- | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `v14.1.4` | `deploymentId` stabilized as top-level config option. | | `v16.2.0` | Pages Router detects version skew from the response header rather than the build ID, and the build ID is constant when `deploymentId` is set. |
| `v13.4.10` | `experimental.deploymentId` introduced. | | `v14.1.4` | `deploymentId` stabilized as top-level config option. |
| `v13.4.10` | `experimental.deploymentId` introduced. |
## Related ## Related
......
...@@ -17,3 +17,5 @@ module.exports = { ...@@ -17,3 +17,5 @@ module.exports = {
}, },
} }
``` ```
> **Good to know:** When [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) is set, Next.js uses a constant build ID and `generateBuildId` has no effect. [Version skew](/docs/app/guides/self-hosting#version-skew) is detected from the deployment ID instead.
...@@ -156,8 +156,8 @@ export default function gumletLoader({ src, width, quality }) { ...@@ -156,8 +156,8 @@ export default function gumletLoader({ src, width, quality }) {
// Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives // Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives
export default function imageengineLoader({ src, width, quality }) { export default function imageengineLoader({ src, width, quality }) {
const compression = 100 - (quality || 50) const compression = 100 - (quality || 50)
const params = [`w_${width}`, `cmpr_${compression}`)] const params = [`w_${width}`, `cmpr_${compression}`]
return `https://example.com${src}?imgeng=/${params.join('/')` return `https://example.com${src}?imgeng=/${params.join('/')}`
} }
``` ```
......
...@@ -6,7 +6,7 @@ description: Configure the Next.js cache used for storing and revalidating data ...@@ -6,7 +6,7 @@ description: Configure the Next.js cache used for storing and revalidating data
You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application. You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application.
> **Good to know**: The `cacheHandler` (singular) configuration is specifically used by Next.js for server cache operations such as storing and revalidating ISR, route handler responses, and optimized images. It is **not** used by `'use cache'` directives. For `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers) (plural) instead. > **Good to know**: The `cacheHandler` (singular) configuration is specifically used by Next.js for server cache operations such as storing and revalidating ISR, route handler responses, and optimized images. It is **not** used by `'use cache'` directives. For `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers) (plural) instead. [`cacheMaxMemorySize`](/docs/app/api-reference/config/next-config-js/cacheMaxMemorySize) is separate from both, and sizes the in-memory cache for each.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
......
...@@ -8,10 +8,10 @@ related: ...@@ -8,10 +8,10 @@ related:
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
- app/api-reference/file-conventions/route-segment-config/prefetch - app/api-reference/file-conventions/route-segment-config/prefetch
- app/api-reference/components/link - app/api-reference/components/link
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
--- ---
`partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; opt individual routes into [runtime prefetching](/docs/app/guides/runtime-prefetching) to fetch more. `partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; set `prefetch={true}` on individual links to use [per-link prefetching](/docs/app/guides/optimizing-prefetching) and fetch more.
## Usage ## Usage
...@@ -46,13 +46,13 @@ module.exports = { ...@@ -46,13 +46,13 @@ module.exports = {
Before Partial Prefetching, Next.js prefetched per visible link: a page with N links to N routes produced ~N route prefetches as those links entered the viewport. Before Partial Prefetching, Next.js prefetched per visible link: a page with N links to N routes produced ~N route prefetches as those links entered the viewport.
With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The shell carries the route's rendered output minus per-link data; specifics like params and search-bound data fill in after navigation. Shells are cached on the client, so a route is fetched once even if many links on the page point at it. With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The App Shell contains rendered output that does not depend on a link's URL. URL-specific content, including content that depends on `params` or `searchParams`, resolves after navigation by default. App Shells are cached on the client, so links to the same route reuse one prefetch.
The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it. The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client. > **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client.
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves URL data like `params`, `searchParams`, and the full URL, and the cached content behind it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
> **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail. > **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail.
......
...@@ -29,7 +29,7 @@ const nextConfig = { ...@@ -29,7 +29,7 @@ const nextConfig = {
}, },
} }
export default nextConfig module.exports = nextConfig
``` ```
## Config Options ## Config Options
......
...@@ -63,7 +63,7 @@ In this case, the `getUserDetails` function returns data about a given user. We ...@@ -63,7 +63,7 @@ In this case, the `getUserDetails` function returns data about a given user. We
```ts switcher ```ts switcher
import { experimental_taintObjectReference } from 'react' import { experimental_taintObjectReference } from 'react'
function getUserDetails(id: string): UserDetails { async function getUserDetails(id: string): Promise<UserDetails> {
const user = await db.queryUserById(id) const user = await db.queryUserById(id)
experimental_taintObjectReference( experimental_taintObjectReference(
...@@ -78,7 +78,7 @@ function getUserDetails(id: string): UserDetails { ...@@ -78,7 +78,7 @@ function getUserDetails(id: string): UserDetails {
```js switcher ```js switcher
import { experimental_taintObjectReference } from 'react' import { experimental_taintObjectReference } from 'react'
function getUserDetails(id) { async function getUserDetails(id) {
const user = await db.queryUserById(id) const user = await db.queryUserById(id)
experimental_taintObjectReference( experimental_taintObjectReference(
...@@ -151,15 +151,15 @@ export async function ContactPage({ params }) { ...@@ -151,15 +151,15 @@ export async function ContactPage({ params }) {
### Tainting a unique value ### Tainting a unique value
In this case, we can access the server configuration by awaiting calls to `config.getConfigDetails`. However, the system configuration contains the `SERVICE_API_KEY` that we don't want to expose to clients. In this case, we can access the server configuration by awaiting calls to `configService.getConfigDetails`. However, the system configuration contains the `SERVICE_API_KEY` that we don't want to expose to clients.
We can taint the `config.SERVICE_API_KEY` value. We can taint the `config.SERVICE_API_KEY` value.
```ts switcher ```ts switcher
import { experimental_taintUniqueValue } from 'react' import { experimental_taintUniqueValue } from 'react'
function getSystemConfig(): SystemConfig { async function getSystemConfig(): Promise<SystemConfig> {
const config = await config.getConfigDetails() const config = await configService.getConfigDetails()
experimental_taintUniqueValue( experimental_taintUniqueValue(
'Do not pass configuration tokens to the client', 'Do not pass configuration tokens to the client',
...@@ -174,8 +174,8 @@ function getSystemConfig(): SystemConfig { ...@@ -174,8 +174,8 @@ function getSystemConfig(): SystemConfig {
```js switcher ```js switcher
import { experimental_taintUniqueValue } from 'react' import { experimental_taintUniqueValue } from 'react'
function getSystemConfig() { async function getSystemConfig() {
const config = await config.getConfigDetails() const config = await configService.getConfigDetails()
experimental_taintUniqueValue( experimental_taintUniqueValue(
'Do not pass configuration tokens to the client', 'Do not pass configuration tokens to the client',
......
...@@ -7,7 +7,7 @@ description: Configure Next.js with Turbopack-specific options ...@@ -7,7 +7,7 @@ description: Configure Next.js with Turbopack-specific options
The `turbopack` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved. The `turbopack` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved.
> **Good to know**: The `turbopack` option was previously named `experimental.turbo` in Next.js versions 13.0.0 to 15.2.x. The `experimental.turbo` option will be removed in Next.js 16. > **Good to know**: The `turbopack` option was previously named `experimental.turbo` in Next.js versions 13.0.0 to 15.2.x, an option which still works as an alias, but new configuration should use the top-level `turbopack` option.
> >
> If you are using an older version of Next.js, run `npx @next/codemod@latest next-experimental-turbo-to-turbopack .` to automatically migrate your configuration. > If you are using an older version of Next.js, run `npx @next/codemod@latest next-experimental-turbo-to-turbopack .` to automatically migrate your configuration.
......
...@@ -4,13 +4,29 @@ description: Configure how Turbopack splits your client-side JavaScript into chu ...@@ -4,13 +4,29 @@ description: Configure how Turbopack splits your client-side JavaScript into chu
version: experimental version: experimental
--- ---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
<AppOnly>
`experimental.turbopackChunking` lets you configure Turbopack's production JavaScript `experimental.turbopackChunking` lets you configure Turbopack's production JavaScript
chunker. These options allow you to change the assumptions the chunker makes about user chunker. These options allow you to change the assumptions the chunker makes about user
behaviour, tweak the raw size thresholds it uses, and enable the experimental component behavior, tweak the raw size thresholds it uses, and enable the experimental component
chunks feature. chunks feature.
</AppOnly>
<PagesOnly>
`experimental.turbopackChunking` lets you configure Turbopack's production JavaScript
chunker. These options allow you to change the assumptions the chunker makes about user
behavior and tweak the raw size thresholds it uses.
</PagesOnly>
By default, Turbopack's chunking is configured as follows: By default, Turbopack's chunking is configured as follows:
<AppOnly>
```ts filename="next.config.ts" switcher ```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -46,6 +62,43 @@ const nextConfig = { ...@@ -46,6 +62,43 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
</AppOnly>
<PagesOnly>
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig = {
experimental: {
turbopackChunking: {
minChunkSize: 50000,
maxChunkCountPerGroup: 40,
maxMergeChunkSize: 200000,
},
},
} satisfies NextConfig
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbopackChunking: {
minChunkSize: 50000,
maxChunkCountPerGroup: 40,
maxMergeChunkSize: 200000,
},
},
}
module.exports = nextConfig
```
</PagesOnly>
## Size Thresholds ## Size Thresholds
The following options control how aggressively Turbopack merges chunks and how large a chunk is The following options control how aggressively Turbopack merges chunks and how large a chunk is
...@@ -69,6 +122,8 @@ When merging chunks, the trade-off being made is an improvement to performance o ...@@ -69,6 +122,8 @@ When merging chunks, the trade-off being made is an improvement to performance o
loads at the cost of navigation performance. This is because each additional network request loads at the cost of navigation performance. This is because each additional network request
being made is costly, however, smaller chunks are more likely to be re-usable across pages. being made is costly, however, smaller chunks are more likely to be re-usable across pages.
<AppOnly>
## Component Chunks ## Component Chunks
Producing component chunks is an experimental feature that aims to give you the initial Producing component chunks is an experimental feature that aims to give you the initial
...@@ -86,6 +141,8 @@ This avoids re-downloading JavaScript the browser already has when navigating. ...@@ -86,6 +141,8 @@ This avoids re-downloading JavaScript the browser already has when navigating.
this size are folded into a single component instead of being emitted on their own, this size are folded into a single component instead of being emitted on their own,
to avoid producing many tiny chunks. to avoid producing many tiny chunks.
</AppOnly>
## Heuristics ## Heuristics
These change the assumptions the chunker makes when weighing whether merging two These change the assumptions the chunker makes when weighing whether merging two
......
...@@ -282,6 +282,7 @@ export function proxy(request: NextRequest) { ...@@ -282,6 +282,7 @@ export function proxy(request: NextRequest) {
```tsx filename="app/some/page.tsx" ```tsx filename="app/some/page.tsx"
import type { Route } from 'next' import type { Route } from 'next'
import Link from 'next/link'
export default function Page() { export default function Page() {
return <Link href={'/proxy-redirect' as Route}>Link Text</Link> return <Link href={'/proxy-redirect' as Route}>Link Text</Link>
......
...@@ -139,7 +139,7 @@ const eslintConfig = defineConfig([ ...@@ -139,7 +139,7 @@ const eslintConfig = defineConfig([
{ {
files: ['**/*.{js,jsx,ts,tsx}'], files: ['**/*.{js,jsx,ts,tsx}'],
plugins: { plugins: {
next: eslintNextPlugin, '@next/next': eslintNextPlugin,
}, },
settings: { settings: {
next: { next: {
......
...@@ -142,7 +142,7 @@ You can view a list of all available examples along with setup instructions in t ...@@ -142,7 +142,7 @@ You can view a list of all available examples along with setup instructions in t
### With any public GitHub example ### With any public GitHub example
To create a new app using any public GitHub example, use the `--example` option with the GitHub repo's URL. For example: To create a new app using any public GitHub example, use the `--example` option with the GitHub repository's URL. For example:
```bash package="pnpm" ```bash package="pnpm"
pnpm create next-app --example "https://github.com/.../" [your-project-name] pnpm create next-app --example "https://github.com/.../" [your-project-name]
......
...@@ -93,22 +93,20 @@ See the [Building guide](/docs/app/guides/building) to learn how to read the out ...@@ -93,22 +93,20 @@ See the [Building guide](/docs/app/guides/building) to learn how to read the out
The following options are available for the `next build` command: The following options are available for the `next build` command:
| Option | Description | | Option | Description |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. | | `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. | | `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. |
| `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. | | `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. |
| `--webpack` | Build using Webpack. | | `--webpack` | Build using Webpack. |
| `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. | | `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. |
| | | `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). | | `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. |
| `--no-lint` | Disables linting. _Note: linting will be removed from `next build` in Next 16. If you're using Next 15.5+ with a linter other than `eslint`, linting during build will not occur._ | | `--experimental-app-only` | Builds only App Router routes. |
| `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. | | `--experimental-build-mode [mode]` | Uses an experimental build mode. (choices: "compile", "generate", default: "default") |
| `--experimental-app-only` | Builds only App Router routes. | | `--debug-prerender` | Debug prerender errors in development. |
| `--experimental-build-mode [mode]` | Uses an experimental build mode. (choices: "compile", "generate", default: "default") | | `--debug-build-paths=<patterns>` | Build only specific routes for debugging. |
| `--debug-prerender` | Debug prerender errors in development. | | `--experimental-cpu-prof` | Enables CPU profiling using V8's inspector. Profiles are saved to `.next-profiles/` on exit. |
| `--debug-build-paths=<patterns>` | Build only specific routes for debugging. |
| `--experimental-cpu-prof` | Enables CPU profiling using V8's inspector. Profiles are saved to `.next-profiles/` on exit. |
### `next start` options ### `next start` options
...@@ -299,7 +297,7 @@ This helps surface more readable stack traces and code frames in the build outpu ...@@ -299,7 +297,7 @@ This helps surface more readable stack traces and code frames in the build outpu
### Building specific routes ### Building specific routes
You can build only specific routes in the App and Pages Routers using the `--debug-build-paths` option. This is useful for faster debugging when working with large applications. The `--debug-build-paths` option accepts comma-separated file paths and supports glob patterns: You can build only specific routes in the App and Pages Routers using the `--debug-build-paths` option. This is useful for faster debugging when working with large applications. The `--debug-build-paths` option accepts comma-separated file paths, supports glob patterns, and excludes any path prefixed with `!`:
```bash filename="Terminal" ```bash filename="Terminal"
# Build a specific route # Build a specific route
...@@ -314,8 +312,13 @@ next build --debug-build-paths="app/(marketing)/about/page.tsx" ...@@ -314,8 +312,13 @@ next build --debug-build-paths="app/(marketing)/about/page.tsx"
# Use glob patterns # Use glob patterns
next build --debug-build-paths="app/**/page.tsx" next build --debug-build-paths="app/**/page.tsx"
next build --debug-build-paths="pages/*.tsx" next build --debug-build-paths="pages/*.tsx"
# Exclude routes with a ! prefix
next build --debug-build-paths="app/**/page.tsx,!app/admin/**"
``` ```
In projects that keep routes under `src/`, paths resolve with or without the `src/` prefix, so both `app/page.tsx` and `src/app/page.tsx` match the same route.
### Changing the default port ### Changing the default port
By default, Next.js uses `http://localhost:3000` during development and with `next start`. The default port can be changed with the `-p` option, like so: By default, Next.js uses `http://localhost:3000` during development and with `next start`. The default port can be changed with the `-p` option, like so:
......
...@@ -48,6 +48,7 @@ export interface NextAdapter { ...@@ -48,6 +48,7 @@ export interface NextAdapter {
onBuildComplete?: (ctx: { onBuildComplete?: (ctx: {
routing: { routing: {
beforeMiddleware: Array<Route> beforeMiddleware: Array<Route>
middlewareMatchers: Array<Route>
beforeFiles: Array<Route> beforeFiles: Array<Route>
afterFiles: Array<Route> afterFiles: Array<Route>
dynamicRoutes: Array<Route> dynamicRoutes: Array<Route>
......
...@@ -24,6 +24,7 @@ Called after the build process completes with detailed information about routes ...@@ -24,6 +24,7 @@ Called after the build process completes with detailed information about routes
- `context.routing`: Object containing Next.js routing phases and metadata - `context.routing`: Object containing Next.js routing phases and metadata
- `routing.beforeMiddleware`: Routes executed before middleware (includes header and redirect handling) - `routing.beforeMiddleware`: Routes executed before middleware (includes header and redirect handling)
- `routing.middlewareMatchers`: Middleware matcher definitions for this build, used to decide whether middleware should be invoked for a given request
- `routing.beforeFiles`: Rewrite routes checked before filesystem route matching - `routing.beforeFiles`: Rewrite routes checked before filesystem route matching
- `routing.afterFiles`: Rewrite routes checked after filesystem route matching - `routing.afterFiles`: Rewrite routes checked after filesystem route matching
- `routing.dynamicRoutes`: Dynamic route matching table - `routing.dynamicRoutes`: Dynamic route matching table
......
...@@ -30,6 +30,7 @@ React pages from the `pages/` directory: ...@@ -30,6 +30,7 @@ React pages from the `pages/` directory:
sourcePage: string // Original source file path in pages/ directory sourcePage: string // Original source file path in pages/ directory
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path) assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path) wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: { edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime modulePath: string // Absolute path to the module registered in the edge runtime
...@@ -57,6 +58,7 @@ API routes from `pages/api/`: ...@@ -57,6 +58,7 @@ API routes from `pages/api/`:
sourcePage: string // Original relative source file path sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path) assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path) wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: { edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime modulePath: string // Absolute path to the module registered in the edge runtime
...@@ -84,6 +86,7 @@ React pages from the `app/` directory: ...@@ -84,6 +86,7 @@ React pages from the `app/` directory:
sourcePage: string // Original relative source file path sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' // Runtime the route is built for runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path) assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path) wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: { edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime modulePath: string // Absolute path to the module registered in the edge runtime
...@@ -111,6 +114,7 @@ API and metadata routes from the `app/` directory: ...@@ -111,6 +114,7 @@ API and metadata routes from the `app/` directory:
sourcePage: string // Original relative source file path sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' // Runtime the route is built for runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path) assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path) wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: { edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime modulePath: string // Absolute path to the module registered in the edge runtime
...@@ -218,6 +222,7 @@ See [Supporting immutable static assets](/docs/app/api-reference/adapters/immuta ...@@ -218,6 +222,7 @@ See [Supporting immutable static assets](/docs/app/api-reference/adapters/immuta
sourcePage: string // Always 'middleware' sourcePage: string // Always 'middleware'
runtime: 'nodejs' | 'edge' // Runtime the route is built for runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path) assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path) wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: { edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime modulePath: string // Absolute path to the module registered in the edge runtime
......
...@@ -9,6 +9,10 @@ The `routing` object in `onBuildComplete` provides complete routing information ...@@ -9,6 +9,10 @@ The `routing` object in `onBuildComplete` provides complete routing information
Routes applied before middleware execution. These include generated header and redirect behavior. Routes applied before middleware execution. These include generated header and redirect behavior.
## `routing.middlewareMatchers`
Middleware matcher definitions emitted for this build. Use these to decide whether middleware should be invoked for a given request.
## `routing.beforeFiles` ## `routing.beforeFiles`
Rewrite routes checked before filesystem route matching. Rewrite routes checked before filesystem route matching.
......
...@@ -4,35 +4,3 @@ description: Build deployment adapters for Next.js platforms and infrastructure. ...@@ -4,35 +4,3 @@ description: Build deployment adapters for Next.js platforms and infrastructure.
--- ---
Use this section to build and validate deployment adapters that integrate with the Next.js build and runtime model. Use this section to build and validate deployment adapters that integrate with the Next.js build and runtime model.
<AppOnly>
- [Configuration](/docs/app/api-reference/adapters/configuration)
- [Creating an Adapter](/docs/app/api-reference/adapters/creating-an-adapter)
- [API Reference](/docs/app/api-reference/adapters/api-reference)
- [Testing Adapters](/docs/app/api-reference/adapters/testing-adapters)
- [Routing with `@next/routing`](/docs/app/api-reference/adapters/routing-with-next-routing)
- [Implementing PPR in an Adapter](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter)
- [Runtime Integration](/docs/app/api-reference/adapters/runtime-integration)
- [Invoking Entrypoints](/docs/app/api-reference/adapters/invoking-entrypoints)
- [Output Types](/docs/app/api-reference/adapters/output-types)
- [Routing Information](/docs/app/api-reference/adapters/routing-information)
- [Use Cases](/docs/app/api-reference/adapters/use-cases)
- [Supporting Immutable Static Assets](/docs/app/api-reference/adapters/immutable-static-assets)
</AppOnly>
<PagesOnly>
- [Configuration](/docs/pages/api-reference/adapters/configuration)
- [Creating an Adapter](/docs/pages/api-reference/adapters/creating-an-adapter)
- [API Reference](/docs/pages/api-reference/adapters/api-reference)
- [Testing Adapters](/docs/pages/api-reference/adapters/testing-adapters)
- [Routing with `@next/routing`](/docs/pages/api-reference/adapters/routing-with-next-routing)
- [Runtime Integration](/docs/pages/api-reference/adapters/runtime-integration)
- [Invoking Entrypoints](/docs/pages/api-reference/adapters/invoking-entrypoints)
- [Output Types](/docs/pages/api-reference/adapters/output-types)
- [Routing Information](/docs/pages/api-reference/adapters/routing-information)
- [Use Cases](/docs/pages/api-reference/adapters/use-cases)
</PagesOnly>
...@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon ...@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon
## App Shell ## App Shell
A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components). A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the default prefetch payload during client navigations, the loading state when a [per-link prefetch](/docs/app/guides/optimizing-prefetching) is not ready, and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).
# B # B
......
...@@ -96,7 +96,7 @@ export default function Page() { ...@@ -96,7 +96,7 @@ export default function Page() {
We recommend using HTML validation like `required` and `type="email"` for basic client-side form validation. We recommend using HTML validation like `required` and `type="email"` for basic client-side form validation.
For more advanced server-side validation, you can use a schema validation library like [zod](https://zod.dev/) to validate the form fields before mutating the data: For more advanced server-side validation, you can use a schema validation library like [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/) to validate the form fields before mutating the data:
```ts filename="pages/api/submit.ts" switcher ```ts filename="pages/api/submit.ts" switcher
import type { NextApiRequest, NextApiResponse } from 'next' import type { NextApiRequest, NextApiResponse } from 'next'
......
...@@ -458,7 +458,7 @@ module.exports = { ...@@ -458,7 +458,7 @@ module.exports = {
The following Image Optimization cloud providers are included: The following Image Optimization cloud providers are included:
- Default: Works automatically with `next dev`, `next start`, or a custom server - Default: Works automatically with `next dev`, `next start`, or a custom server
- [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/concepts/image-optimization?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) - [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/image-optimization?utm_source=next-site&utm_medium=docs&utm_campaign=next-website)
- [Imgix](https://www.imgix.com): `loader: 'imgix'` - [Imgix](https://www.imgix.com): `loader: 'imgix'`
- [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'` - [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
- [Akamai](https://www.akamai.com): `loader: 'akamai'` - [Akamai](https://www.akamai.com): `loader: 'akamai'`
......
---
title: catchError
description: API Reference for the catchError function.
source: app/api-reference/functions/catchError
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: turbopackChunking
description: Configure how Turbopack splits your client-side JavaScript into chunks in production.
version: experimental
source: app/api-reference/config/next-config-js/turbopackChunking
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -17,17 +17,16 @@ kind: insight ...@@ -17,17 +17,16 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a Client Component called a navigation hook ([`usePathname`](https://preview.nextjs.org/docs/app/api-reference/functions/use-pathname), [`useParams`](https://preview.nextjs.org/docs/app/api-reference/functions/use-params), [`useSearchParams`](https://preview.nextjs.org/docs/app/api-reference/functions/use-search-params#prerendering), [`useSelectedLayoutSegment`](https://preview.nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment), or [`useSelectedLayoutSegments`](https://preview.nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments)) outside of a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js prerenders as much of a route as possible before a request arrives. These hooks read URL data that is not available during prerendering, so the component needs a fallback to include in the [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell). During [prerendering](/docs/app/glossary#prerendering), a Client Component called a navigation hook ([`usePathname`](/docs/app/api-reference/functions/use-pathname), [`useParams`](/docs/app/api-reference/functions/use-params), [`useSearchParams`](/docs/app/api-reference/functions/use-search-params#prerendering), [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment), or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments)) outside of a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js prerenders as much of a route as possible before a request arrives. These hooks read URL data that is not available during prerendering, so the component needs a fallback to include in the [static shell](/docs/app/glossary#static-shell).
The `useSearchParams` hook triggers this error on any prerendered route because search params come from the request URL. The other four hooks trigger it when the route has dynamic params and is rendered per-request. The `useSearchParams` hook triggers this error on any prerendered route because search params come from the request URL. The other four hooks trigger it when the route has dynamic params and is rendered per-request.
Server-side request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers)) have different fixes. See [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime). For unstable values like [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) in Client Components, see [Next.js encountered the unstable value Math.random() in a Client Component](/docs/messages/blocking-prerender-random-client). Server-side request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers)) have different fixes. See [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime). For unstable values like [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) in Client Components, see [Next.js encountered the unstable value Math.random() in a Client Component](/docs/messages/blocking-prerender-random-client).
## Ways to fix this ## Ways to fix this
...@@ -90,7 +89,7 @@ export function Search() { ...@@ -90,7 +89,7 @@ export function Search() {
} }
``` ```
Learn more: [`useSearchParams` prerendering behavior](https://preview.nextjs.org/docs/app/api-reference/functions/use-search-params#prerendering) Learn more: [`useSearchParams` prerendering behavior](/docs/app/api-reference/functions/use-search-params#prerendering)
#### Push the hook read down to the leaf #### Push the hook read down to the leaf
...@@ -150,7 +149,7 @@ The nav links prerender into the static shell with their final `href` and label. ...@@ -150,7 +149,7 @@ The nav links prerender into the static shell with their final `href` and label.
To style the parent `<Link>` itself instead (for example, bolding the active label), have the leaf set `data-active` and read it from the parent with `has-data-active:font-bold`. To style the parent `<Link>` itself instead (for example, bolding the active label), have the leaf set `data-active` and read it from the parent with `has-data-active:font-bold`.
Learn more: [`usePathname`](https://preview.nextjs.org/docs/app/api-reference/functions/use-pathname), [Creating an active link component with `useSelectedLayoutSegment`](https://preview.nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment#creating-an-active-link-component) Learn more: [`usePathname`](/docs/app/api-reference/functions/use-pathname), [Creating an active link component with `useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment#creating-an-active-link-component)
#### Wrap a sibling that uses the hook value #### Wrap a sibling that uses the hook value
...@@ -193,20 +192,20 @@ The sibling renders nothing visible, so an empty fallback is correct. There is n ...@@ -193,20 +192,20 @@ The sibling renders nothing visible, so an empty fallback is correct. There is n
### Trade-off ### Trade-off
The user sees the fallback on the first paint of the suspended region, then it swaps to the real value once the hook resolves after hydration. Choose a fallback shape that matches the final layout so the swap doesn't cause a layout shift. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The user sees the fallback on the first paint of the suspended region, then it swaps to the real value once the hook resolves after hydration. Choose a fallback shape that matches the final layout so the swap doesn't cause a layout shift. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Place the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the hook call as possible. Wrapping a large subtree forces the entire subtree into the fallback and loses prerendered content. - Place the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the hook call as possible. Wrapping a large subtree forces the entire subtree into the fallback and loses prerendered content.
- The fallback must be synchronous and deterministic. Do not call [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), or [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) inside it. Each one raises a separate [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering. - The fallback must be synchronous and deterministic. Do not call [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), or [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) inside it. Each one raises a separate [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering.
- Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`. - Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`.
- A nav rendered in a layout suspends on any page below it that reads URL data the layout's static shell doesn't know. Push the hook read down to the smallest leaf that needs the value so the rest of the nav stays prerendered. - A nav rendered in a layout suspends on any page below it that reads URL data the layout's static shell doesn't know. Push the hook read down to the smallest leaf that needs the value so the rest of the nav stays prerendered.
- The static shell does not include the active state. The fallback paints first, then the indicator hydrates and the active style appears. For active-link patterns where the flash is visible, add an [inline script that runs before paint](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) to set the active attribute from `location.pathname` so the correct link is styled on the first paint. - The static shell does not include the active state. The fallback paints first, then the indicator hydrates and the active style appears. For active-link patterns where the flash is visible, add an [inline script that runs before paint](/docs/app/guides/preventing-flash-before-hydration) to set the active attribute from `location.pathname` so the correct link is styled on the first paint.
- [`usePathname`](https://preview.nextjs.org/docs/app/api-reference/functions/use-pathname#avoid-hydration-mismatch-with-rewrites) reads the source path on the server when the request was rewritten in `next.config` or middleware, while the browser sees the rewritten path. The active state on a rewritten route resolves to the wrong link on the server and corrects itself on hydration. If your app uses rewrites, defer the read until after mount as the [docs recommend](https://preview.nextjs.org/docs/app/api-reference/functions/use-pathname#avoid-hydration-mismatch-with-rewrites). - [`usePathname`](/docs/app/api-reference/functions/use-pathname#avoid-hydration-mismatch-with-rewrites) reads the source path on the server when the request was rewritten in `next.config` or middleware, while the browser sees the rewritten path. The active state on a rewritten route resolves to the wrong link on the server and corrects itself on hydration. If your app uses rewrites, defer the read until after mount as the [docs recommend](/docs/app/api-reference/functions/use-pathname#avoid-hydration-mismatch-with-rewrites).
## Allow blocking route ## Allow blocking route
Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes. Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes.
### Patterns ### Patterns
...@@ -222,11 +221,11 @@ export default function Page() { ...@@ -222,11 +221,11 @@ export default function Page() {
} }
``` ```
Learn more: [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation). Learn more: [Ensuring instant navigations](/docs/app/guides/instant-navigation).
#### Opt the layout out #### Opt the layout out
When the shared layout itself can't ship instantly (it reads URL data of its own that has no meaningful fallback), set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated. When the shared layout itself can't ship instantly (it reads URL data of its own that has no meaningful fallback), set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
export const instant = false export const instant = false
...@@ -236,11 +235,11 @@ export default function DashboardLayout({ children }) { ...@@ -236,11 +235,11 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use either pattern when: Use either pattern when:
- The route needs request-time data high in the tree to decide what to render, so there is no meaningful [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) worth showing first. - The route needs request-time data high in the tree to decide what to render, so there is no meaningful [static shell](/docs/app/glossary#static-shell) worth showing first.
- You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today. - You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today.
For a client-hook error this is rarely the right answer. The hook reads a small piece of URL data, and a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around that read keeps the rest of the route prerendered. Choose [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when feasible. For a client-hook error this is rarely the right answer. The hook reads a small piece of URL data, and a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around that read keeps the rest of the route prerendered. Choose [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when feasible.
...@@ -251,23 +250,23 @@ Navigations to this route are not instant. The user waits for the full server re ...@@ -251,23 +250,23 @@ Navigations to this route are not instant. The user waits for the full server re
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- This export does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route. - This export does not disable [prerendering](/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,10 +17,9 @@ kind: insight ...@@ -17,10 +17,9 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called a synchronous [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) API that produces a random value ([`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake an unpredictable value into the prerendered HTML. The SSR value won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client. A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called a synchronous [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) API that produces a random value ([`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake an unpredictable value into the prerendered HTML. The SSR value won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client.
...@@ -85,15 +84,15 @@ export function CorrelationId() { ...@@ -85,15 +84,15 @@ export function CorrelationId() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling a crypto API in any of them raises this same error. Use stable placeholder content. - Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling a crypto API in any of them raises this same error. Use stable placeholder content.
- The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the value only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead. - The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the value only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead.
- A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using the crypto API re-renders on the client (a parent state change, a context update), it produces a new value each time. To stabilize the value across re-renders, call the crypto API once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop. - A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using the crypto API re-renders on the client (a parent state change, a context update), it produces a new value each time. To stabilize the value across re-renders, call the crypto API once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop.
...@@ -188,7 +187,7 @@ Learn more: [`useRef`](https://react.dev/reference/react/useRef). ...@@ -188,7 +187,7 @@ Learn more: [`useRef`](https://react.dev/reference/react/useRef).
### Trade-off ### Trade-off
The user sees the placeholder briefly before the real value. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The user sees the placeholder briefly before the real value. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -201,7 +200,7 @@ The user sees the placeholder briefly before the real value. For interactions th ...@@ -201,7 +200,7 @@ The user sees the placeholder briefly before the real value. For interactions th
### Suspend with `use(io())` ### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/request-id.js" ```jsx filename="app/components/request-id.js"
'use client' 'use client'
...@@ -229,17 +228,17 @@ export default function Page() { ...@@ -229,17 +228,17 @@ export default function Page() {
} }
``` ```
Learn more: [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io). Learn more: [`io`](/docs/app/api-reference/functions/io).
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,13 +17,12 @@ kind: insight ...@@ -17,13 +17,12 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a Server Component called a synchronous [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) or Node [`crypto`](https://nodejs.org/api/crypto.html) API that produces a random value ([`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), [`crypto.randomBytes()`](https://nodejs.org/api/crypto.html#cryptorandombytessize-callback), [`crypto.generateKeyPairSync()`](https://nodejs.org/api/crypto.html#cryptogeneratekeypairsynctype-options)) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake an unpredictable value into the prerendered HTML. The value at build time will differ from the value at runtime, so you need to choose: cache the generated value so it's stable, defer the call behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client. During [prerendering](/docs/app/glossary#prerendering), a Server Component called a synchronous [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) or Node [`crypto`](https://nodejs.org/api/crypto.html) API that produces a random value ([`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), [`crypto.randomBytes()`](https://nodejs.org/api/crypto.html#cryptorandombytessize-callback), [`crypto.generateKeyPairSync()`](https://nodejs.org/api/crypto.html#cryptogeneratekeypairsynctype-options)) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake an unpredictable value into the prerendered HTML. The value at build time will differ from the value at runtime, so you need to choose: cache the generated value so it's stable, defer the call behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client.
Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)) have parallel error pages: see [`Math.random()`](/docs/messages/blocking-prerender-random) and [`Date.now()`](/docs/messages/blocking-prerender-current-time). The Client Component case is handled at [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client). Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)) have parallel error pages: see [`Math.random()`](/docs/messages/blocking-prerender-random) and [`Date.now()`](/docs/messages/blocking-prerender-current-time). The Client Component case is handled at [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client).
...@@ -64,13 +63,13 @@ Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/ ...@@ -64,13 +63,13 @@ Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/
## Generate on every request ## Generate on every request
Choose this fix when each request needs a fresh token: a session ID, an OAuth state, a single-use nonce, a CSRF token. Add [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request. Choose this fix when each request needs a fresh token: a session ID, an OAuth state, a single-use nonce, a CSRF token. Add [`await connection()`](/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request.
### Patterns ### Patterns
#### Use `await connection()` before the crypto call #### Use `await connection()` before the crypto call
Call [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before the crypto API. Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in. Call [`connection()`](/docs/app/api-reference/functions/connection) before the crypto API. Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in.
Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the crypto call as possible. If the parent has cached content, isolate the crypto read in its own component so only that piece falls behind the boundary. Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the crypto call as possible. If the parent has cached content, isolate the crypto read in its own component so only that piece falls behind the boundary.
...@@ -100,7 +99,7 @@ export async function CsrfToken() { ...@@ -100,7 +99,7 @@ export async function CsrfToken() {
#### Alternative: `await io()` #### Alternative: `await io()`
Use [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/csrf-token.js" ```jsx filename="app/dashboard/csrf-token.js"
import { io } from 'next/cache' import { io } from 'next/cache'
...@@ -111,11 +110,11 @@ export async function CsrfToken() { ...@@ -111,11 +110,11 @@ export async function CsrfToken() {
} }
``` ```
Learn more: [`connection`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io), [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [`connection`](/docs/app/api-reference/functions/connection), [`io`](/docs/app/api-reference/functions/io), [Streaming](/docs/app/guides/streaming).
#### Switch to an async crypto API #### Switch to an async crypto API
When an async equivalent of the API exists, prefer it. Async crypto operations integrate with [`<Suspense>`](https://react.dev/reference/react/Suspense) naturally and don't need [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection): the [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) already tells Next.js the surrounding scope is request-time. When an async equivalent of the API exists, prefer it. Async crypto operations integrate with [`<Suspense>`](https://react.dev/reference/react/Suspense) naturally and don't need [`await connection()`](/docs/app/api-reference/functions/connection): the [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) already tells Next.js the surrounding scope is request-time.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { randomBytes } from 'node:crypto' import { randomBytes } from 'node:crypto'
...@@ -142,11 +141,11 @@ Learn more: [Node `crypto` API](https://nodejs.org/docs/latest/api/crypto.html). ...@@ -142,11 +141,11 @@ Learn more: [Node `crypto` API](https://nodejs.org/docs/latest/api/crypto.html).
### Trade-off ### Trade-off
The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it paints. When the fallback is visible UI, design it to approximate the final layout so it doesn't cause a layout shift when the content arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it paints. When the fallback is visible UI, design it to approximate the final layout so it doesn't cause a layout shift when the content arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling a crypto API in any of them raises this same error. - Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling a crypto API in any of them raises this same error.
- For genuinely security-critical tokens (session IDs, CSRF), [Generate on every request](#generate-on-every-request) is the only correct choice. Caching a CSRF token across visitors defeats its purpose. - For genuinely security-critical tokens (session IDs, CSRF), [Generate on every request](#generate-on-every-request) is the only correct choice. Caching a CSRF token across visitors defeats its purpose.
- This error only fires for synchronous random-producing APIs. Async crypto operations ([`crypto.subtle.digest()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest), [`crypto.generateKeyPair()`](https://nodejs.org/api/crypto.html#cryptogeneratekeypairtype-options-callback)) integrate with [`<Suspense>`](https://react.dev/reference/react/Suspense) naturally and don't trip the error. - This error only fires for synchronous random-producing APIs. Async crypto operations ([`crypto.subtle.digest()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest), [`crypto.generateKeyPair()`](https://nodejs.org/api/crypto.html#cryptogeneratekeypairtype-options-callback)) integrate with [`<Suspense>`](https://react.dev/reference/react/Suspense) naturally and don't trip the error.
...@@ -158,7 +157,7 @@ Choose this fix when the generated value is a _key into another cached operation ...@@ -158,7 +157,7 @@ Choose this fix when the generated value is a _key into another cached operation
#### Cache the token alongside the query that uses it #### Cache the token alongside the query that uses it
Wrap both the token generation and the call that consumes it in the same [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) function. Wrap both the token generation and the call that consumes it in the same [`use cache`](/docs/app/api-reference/directives/use-cache) function.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
async function getCachedData() { async function getCachedData() {
...@@ -173,11 +172,11 @@ export default async function Page() { ...@@ -173,11 +172,11 @@ export default async function Page() {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache).
#### Tag the cache for explicit rotation #### Tag the cache for explicit rotation
When you want to rotate the token on a schedule or in response to an event, tag the entry with [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag). Invalidate from a Server Action with [`updateTag`](/docs/app/api-reference/functions/updateTag) (read-your-own-writes: the next request waits for fresh data) or from a Route Handler with [`revalidateTag`](https://preview.nextjs.org/docs/app/api-reference/functions/revalidateTag) (stale-while-revalidate). When you want to rotate the token on a schedule or in response to an event, tag the entry with [`cacheTag`](/docs/app/api-reference/functions/cacheTag). Invalidate from a Server Action with [`updateTag`](/docs/app/api-reference/functions/updateTag) (read-your-own-writes: the next request waits for fresh data) or from a Route Handler with [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) (stale-while-revalidate).
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { cacheTag } from 'next/cache' import { cacheTag } from 'next/cache'
...@@ -189,7 +188,7 @@ async function getApiToken() { ...@@ -189,7 +188,7 @@ async function getApiToken() {
} }
``` ```
Learn more: [How revalidation works](https://preview.nextjs.org/docs/app/guides/how-revalidation-works). Learn more: [How revalidation works](/docs/app/guides/how-revalidation-works).
### Trade-off ### Trade-off
...@@ -198,12 +197,12 @@ Every visitor in the cache window uses the same generated value. That's the righ ...@@ -198,12 +197,12 @@ Every visitor in the cache window uses the same generated value. That's the righ
### Gotchas ### Gotchas
- Don't cache a value that's intended as a security token for visitors. If the same "random" UUID is used as a CSRF token for every user, the protection is gone. - Don't cache a value that's intended as a security token for visitors. If the same "random" UUID is used as a CSRF token for every user, the protection is gone.
- [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) can't combine with [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) in the same scope, so you can't key the cached value by user identity from inside the cached function. - [`use cache`](/docs/app/api-reference/directives/use-cache) can't combine with [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) in the same scope, so you can't key the cached value by user identity from inside the cached function.
- If you cache a function and still see this error, the [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches). - If you cache a function and still see this error, the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches).
### Short-lived caches ### Short-lived caches
[`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](https://preview.nextjs.org/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming. [`use cache`](/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming.
To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead. To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead.
...@@ -240,7 +239,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp ...@@ -240,7 +239,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp
### Trade-off ### Trade-off
The first paint shows the SSR fallback (often `null`), and the value appears only after the browser hydrates the component. That's fine for client-only state but wrong for tokens that have to be in the prerendered HTML. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The first paint shows the SSR fallback (often `null`), and the value appears only after the browser hydrates the component. That's fine for client-only state but wrong for tokens that have to be in the prerendered HTML. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -251,11 +250,11 @@ The first paint shows the SSR fallback (often `null`), and the value appears onl ...@@ -251,11 +250,11 @@ The first paint shows the SSR fallback (often `null`), and the value appears onl
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,14 +17,15 @@ kind: insight ...@@ -17,14 +17,15 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake "now" into the prerendered HTML. The SSR timestamp won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client. A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake "now" into the prerendered HTML. The SSR timestamp won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client.
An imported library can also read the current time during render. In that case, the stack trace may point to the hook or component that initializes the library instead of its internal `Date.now()` call.
The Server Component case is handled at [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time). Other unpredictable client-side APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client) and [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client). The Server Component case is handled at [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time). Other unpredictable client-side APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client) and [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client).
## Ways to fix this ## Ways to fix this
...@@ -98,15 +99,15 @@ export function RelativeTime({ timestamp }) { ...@@ -98,15 +99,15 @@ export function RelativeTime({ timestamp }) {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error. Use stable placeholder content. - Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error. Use stable placeholder content.
- The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the timestamp only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead. - The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the timestamp only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead.
- A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) re-renders on the client (a parent state change, a context update), it reads a fresh timestamp each time. To stabilize the value across re-renders, capture [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop. - A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) re-renders on the client (a parent state change, a context update), it reads a fresh timestamp each time. To stabilize the value across re-renders, capture [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop.
...@@ -168,7 +169,7 @@ export function Snapshot() { ...@@ -168,7 +169,7 @@ export function Snapshot() {
### Trade-off ### Trade-off
The user sees the placeholder briefly before the real timestamp. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The user sees the placeholder briefly before the real timestamp. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -218,7 +219,7 @@ Learn more: [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/A ...@@ -218,7 +219,7 @@ Learn more: [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/A
### Cache the value in a Server Component ### Cache the value in a Server Component
When the timestamp doesn't need to reflect the user's current visit and lives inside a Client Component only because of where it's rendered, lift the read into a Server Component above with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). The canonical case is a copyright year in a footer. When the timestamp doesn't need to reflect the user's current visit and lives inside a Client Component only because of where it's rendered, lift the read into a Server Component above with [`use cache`](/docs/app/api-reference/directives/use-cache). The canonical case is a copyright year in a footer.
```jsx filename="app/layout.js" ```jsx filename="app/layout.js"
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -243,7 +244,7 @@ Learn more: [`Date.now()` during prerendering](/docs/messages/blocking-prerender ...@@ -243,7 +244,7 @@ Learn more: [`Date.now()` during prerendering](/docs/messages/blocking-prerender
### Suspend with `use(io())` ### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/last-updated.js" ```jsx filename="app/components/last-updated.js"
'use client' 'use client'
...@@ -271,17 +272,17 @@ export default function Page() { ...@@ -271,17 +272,17 @@ export default function Page() {
} }
``` ```
Learn more: [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io). Learn more: [`io`](/docs/app/api-reference/functions/io).
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,13 +17,12 @@ kind: insight ...@@ -17,13 +17,12 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a Server Component called [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake "now" into the prerendered HTML. The timestamp at build time will be stale at runtime, so you need to choose: cache the value (treat it as "now-ish" with a tolerated drift), defer the read behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client. During [prerendering](/docs/app/glossary#prerendering), a Server Component called [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake "now" into the prerendered HTML. The timestamp at build time will be stale at runtime, so you need to choose: cache the value (treat it as "now-ish" with a tolerated drift), defer the read behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client.
Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: see [`Math.random()`](/docs/messages/blocking-prerender-random) and [crypto APIs](/docs/messages/blocking-prerender-crypto). The Client Component case is handled at [`Date.now()` in a Client Component](/docs/messages/blocking-prerender-current-time-client). Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: see [`Math.random()`](/docs/messages/blocking-prerender-random) and [crypto APIs](/docs/messages/blocking-prerender-crypto). The Client Component case is handled at [`Date.now()` in a Client Component](/docs/messages/blocking-prerender-current-time-client).
...@@ -74,13 +73,13 @@ Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/ ...@@ -74,13 +73,13 @@ Other unpredictable APIs ([`Math.random()`](https://developer.mozilla.org/en-US/
## Generate on every request ## Generate on every request
Choose this fix when the user needs to see the current time. A "last updated at" banner, a server-issued timestamp on a transaction, a "happy new year" banner that flips at midnight. Add [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request. Choose this fix when the user needs to see the current time. A "last updated at" banner, a server-issued timestamp on a transaction, a "happy new year" banner that flips at midnight. Add [`await connection()`](/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request.
### Patterns ### Patterns
#### Use `await connection()` before the timestamp read #### Use `await connection()` before the timestamp read
Call [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before the [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) call. Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in. Call [`connection()`](/docs/app/api-reference/functions/connection) before the [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) call. Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in.
Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the timestamp read as possible. If the parent has cached content (metrics, headers, navigation), isolate the timestamp in its own component so only that piece falls behind the boundary. Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the timestamp read as possible. If the parent has cached content (metrics, headers, navigation), isolate the timestamp in its own component so only that piece falls behind the boundary.
...@@ -110,7 +109,7 @@ export async function UpdatedAt() { ...@@ -110,7 +109,7 @@ export async function UpdatedAt() {
#### Alternative: `await io()` #### Alternative: `await io()`
Use [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/updated-at.js" ```jsx filename="app/dashboard/updated-at.js"
import { io } from 'next/cache' import { io } from 'next/cache'
...@@ -121,26 +120,26 @@ export async function UpdatedAt() { ...@@ -121,26 +120,26 @@ export async function UpdatedAt() {
} }
``` ```
Learn more: [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io), [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [`io`](/docs/app/api-reference/functions/io), [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it paints. Design the fallback so it approximates the final layout. A generic spinner or empty box causes a layout shift when the content arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it paints. Design the fallback so it approximates the final layout. A generic spinner or empty box causes a layout shift when the content arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error. - Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error.
- If you're showing a relative time ("3 minutes ago"), the relative formatting belongs on the client so it can update without a re-render. See [Render on the client](#render-on-the-client). - If you're showing a relative time ("3 minutes ago"), the relative formatting belongs on the client so it can update without a re-render. See [Render on the client](#render-on-the-client).
## Cache the timestamp ## Cache the timestamp
Choose this fix when a stale timestamp is acceptable for the cache window. A "last refreshed" footer on a daily report, an "as of" banner on an hourly chart. Move the [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) call into a function with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Next.js evaluates the function once per cache key and reuses the result. Choose this fix when a stale timestamp is acceptable for the cache window. A "last refreshed" footer on a daily report, an "as of" banner on an hourly chart. Move the [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) call into a function with [`use cache`](/docs/app/api-reference/directives/use-cache). Next.js evaluates the function once per cache key and reuses the result.
### Patterns ### Patterns
#### Cache the producer function #### Cache the producer function
Wrap the timestamp read in a function with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). The returned value is part of the cache entry, so every consumer sees the same timestamp until the cache is invalidated. Wrap the timestamp read in a function with [`use cache`](/docs/app/api-reference/directives/use-cache). The returned value is part of the cache entry, so every consumer sees the same timestamp until the cache is invalidated.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
async function getRenderedAt() { async function getRenderedAt() {
...@@ -154,7 +153,7 @@ export default async function Page() { ...@@ -154,7 +153,7 @@ export default async function Page() {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache).
#### Cache the timestamp alongside the data it relates to #### Cache the timestamp alongside the data it relates to
...@@ -198,7 +197,7 @@ export default async function Layout({ children }) { ...@@ -198,7 +197,7 @@ export default async function Layout({ children }) {
#### Set the rotation window with `cacheLife` #### Set the rotation window with `cacheLife`
When you want the timestamp to refresh on a schedule, set a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. When you want the timestamp to refresh on a schedule, set a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -210,7 +209,7 @@ async function getHourlyTimestamp() { ...@@ -210,7 +209,7 @@ async function getHourlyTimestamp() {
} }
``` ```
Learn more: [How to configure cache lifetimes](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife). Learn more: [How to configure cache lifetimes](/docs/app/api-reference/functions/cacheLife).
### Trade-off ### Trade-off
...@@ -219,11 +218,11 @@ Every visitor in the cache window sees the same timestamp. That's fine for "as o ...@@ -219,11 +218,11 @@ Every visitor in the cache window sees the same timestamp. That's fine for "as o
### Gotchas ### Gotchas
- A cached timestamp is the time of the most recent cache miss, not the time of the current visit. If users expect the displayed time to match their visit, use [Generate on every request](#generate-on-every-request) instead. - A cached timestamp is the time of the most recent cache miss, not the time of the current visit. If users expect the displayed time to match their visit, use [Generate on every request](#generate-on-every-request) instead.
- If you cache a function and still see this error, the [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches). - If you cache a function and still see this error, the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches).
### Short-lived caches ### Short-lived caches
[`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](https://preview.nextjs.org/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming. [`use cache`](/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming.
To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead. To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead.
...@@ -266,7 +265,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp ...@@ -266,7 +265,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp
### Trade-off ### Trade-off
The first paint shows the SSR fallback (often `null` or an em-dash), and the timestamp appears only after the browser hydrates the component. That's fine for time-of-day displays but wrong for timestamps that have to be in the prerendered HTML. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The first paint shows the SSR fallback (often `null` or an em-dash), and the timestamp appears only after the browser hydrates the component. That's fine for time-of-day displays but wrong for timestamps that have to be in the prerendered HTML. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -308,11 +307,11 @@ Learn more: [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/A ...@@ -308,11 +307,11 @@ Learn more: [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/A
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,17 +17,16 @@ kind: insight ...@@ -17,17 +17,16 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) request, database call, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), or other asynchronous IO ran outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't prerender the part of the tree that depends on this data, so navigations to this route block instead of being [instant](https://preview.nextjs.org/docs/app/guides/instant-navigation). During [prerendering](/docs/app/glossary#prerendering), a [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) request, database call, [`await connection()`](/docs/app/api-reference/functions/connection), or other asynchronous IO ran outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't prerender the part of the tree that depends on this data, so navigations to this route block instead of being [instant](/docs/app/guides/instant-navigation).
Request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)) have different fixes. See [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime). Request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)) have different fixes. See [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime).
This error can also appear during a client-side navigation when the data access sits inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary from a parent layout but that boundary is too high. It wraps the entire segment instead of only the dynamic part, so the navigation still blocks. Push the boundary closer to the data access so the rest of the segment stays in the [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell). See [Choosing where to place the boundary](#choosing-where-to-place-the-boundary). This error can also appear during a client-side navigation when the data access sits inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary from a parent layout but that boundary is too high. It wraps the entire segment instead of only the dynamic part, so the navigation still blocks. Push the boundary closer to the data access so the rest of the segment stays in the [static shell](/docs/app/glossary#static-shell). See [Choosing where to place the boundary](#choosing-where-to-place-the-boundary).
## Ways to fix this ## Ways to fix this
...@@ -65,7 +64,7 @@ This error can also appear during a client-side navigation when the data access ...@@ -65,7 +64,7 @@ This error can also appear during a client-side navigation when the data access
## Wrap in or move into Suspense ## Wrap in or move into Suspense
Choose this fix when the data must be fresh on every request. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary lets the static shell ship instantly while the dynamic region [streams](https://preview.nextjs.org/docs/app/glossary#streaming) in once the data resolves. Choose this fix when the data must be fresh on every request. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary lets the static shell ship instantly while the dynamic region [streams](/docs/app/glossary#streaming) in once the data resolves.
### Patterns ### Patterns
...@@ -87,7 +86,7 @@ export default function Page() { ...@@ -87,7 +86,7 @@ export default function Page() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
#### Push the data access down to the leaf #### Push the data access down to the leaf
...@@ -115,7 +114,7 @@ export async function LatestTransactions() { ...@@ -115,7 +114,7 @@ export async function LatestTransactions() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
#### Add a boundary per leaf so they stream in parallel #### Add a boundary per leaf so they stream in parallel
...@@ -138,11 +137,11 @@ export default function Page() { ...@@ -138,11 +137,11 @@ export default function Page() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
#### Use `loading.js` for the whole segment #### Use `loading.js` for the whole segment
When the entire page depends on the failing data access and there's nothing static to render above it, a [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading) file in the segment is the shorthand. Next.js wraps `{children}` of the layout in `<Suspense>` automatically. When the entire page depends on the failing data access and there's nothing static to render above it, a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file in the segment is the shorthand. Next.js wraps `{children}` of the layout in `<Suspense>` automatically.
```jsx filename="app/dashboard/loading.js" ```jsx filename="app/dashboard/loading.js"
export default function Loading() { export default function Loading() {
...@@ -152,11 +151,11 @@ export default function Loading() { ...@@ -152,11 +151,11 @@ export default function Loading() {
> **Good to know**: A `loading.js` file wraps the segment's `{children}` in one Suspense boundary. Parent layouts above it still prerender, but everything inside the segment sits behind the fallback. If page-level content could be prerendered (a static intro, a known title), use explicit `<Suspense>` boundaries inside `page.js` around only the dynamic parts. > **Good to know**: A `loading.js` file wraps the segment's `{children}` in one Suspense boundary. Parent layouts above it still prerender, but everything inside the segment sits behind the fallback. If page-level content could be prerendered (a static intro, a known title), use explicit `<Suspense>` boundaries inside `page.js` around only the dynamic parts.
Learn more: [`loading.js` and instant loading states](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading). Learn more: [`loading.js` and instant loading states](/docs/app/api-reference/file-conventions/loading).
### Trade-off ### Trade-off
The shell ships immediately, but the user sees a loading state for the streamed region on every request. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The shell ships immediately, but the user sees a loading state for the streamed region on every request. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Choosing where to place the boundary ### Choosing where to place the boundary
...@@ -165,27 +164,27 @@ The location of the boundary controls what the user sees during the navigation: ...@@ -165,27 +164,27 @@ The location of the boundary controls what the user sees during the navigation:
- A high boundary (around the whole page) gives one loading state for everything. Less work to set up, but the user loses context about where they were going. - A high boundary (around the whole page) gives one loading state for everything. Less work to set up, but the user loses context about where they were going.
- A low boundary (around the specific component that fetches) keeps surrounding content visible and only shows a fallback for the part that is in flight. Preferred when the surrounding shell has cached content. - A low boundary (around the specific component that fetches) keeps surrounding content visible and only shows a fallback for the part that is in flight. Preferred when the surrounding shell has cached content.
A useful rule: **push the boundary as low as possible** while keeping the fallback meaningful. The cached content above the boundary becomes part of the [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) on navigation. Wrapping individual pieces or wrapping the whole page in one boundary stream the same way, but a lower boundary keeps more prerendered content visible during the navigation. See [Maximizing the static shell](https://preview.nextjs.org/docs/app/getting-started/caching#streaming-uncached-data) for the canonical pattern. A useful rule: **push the boundary as low as possible** while keeping the fallback meaningful. The cached content above the boundary becomes part of the [static shell](/docs/app/glossary#static-shell) on navigation. Wrapping individual pieces or wrapping the whole page in one boundary stream the same way, but a lower boundary keeps more prerendered content visible during the navigation. See [Maximizing the static shell](/docs/app/getting-started/caching#streaming-uncached-data) for the canonical pattern.
### Gotchas ### Gotchas
- The fallback must be deterministic. Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) inside the fallback raises a separate [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering. - The fallback must be deterministic. Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) inside the fallback raises a separate [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering.
- Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or an uncached [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`. - Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](/docs/app/api-reference/functions/cookies) or an uncached [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`.
- If the failing route is `/_not-found` and you don't have a `not-found.tsx` file, the read is in the root layout. `/_not-found` is a real prerendered route that inherits the root layout, so an uncached read there fails on the synthetic route too. Run `next build --debug-prerender` to confirm the originating file, and fix it at the layout, not by adding a `not-found.tsx`. - If the failing route is `/_not-found` and you don't have a `not-found.tsx` file, the read is in the root layout. `/_not-found` is a real prerendered route that inherits the root layout, so an uncached read there fails on the synthetic route too. Run `next build --debug-prerender` to confirm the originating file, and fix it at the layout, not by adding a `not-found.tsx`.
- Boundary placement affects client navigations between sibling routes differently than initial page loads. Validation surfaces this in the dev server and at build time. See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. - Boundary placement affects client navigations between sibling routes differently than initial page loads. Validation surfaces this in the dev server and at build time. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
- Root-element attributes (`<html lang>`, `<html dir>`, `<html data-theme>`) can't be wrapped in `<Suspense>`. You can't suspend the document root, and a boundary inside `<html>` still leaves the attribute itself server-cookie-dependent. Move the read to a pre-paint client script per [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) and add `suppressHydrationWarning` on `<html>` so React doesn't flag the script's mutation as a mismatch. - Root-element attributes (`<html lang>`, `<html dir>`, `<html data-theme>`) can't be wrapped in `<Suspense>`. You can't suspend the document root, and a boundary inside `<html>` still leaves the attribute itself server-cookie-dependent. Move the read to a pre-paint client script per [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) and add `suppressHydrationWarning` on `<html>` so React doesn't flag the script's mutation as a mismatch.
## Cache the component or data ## Cache the component or data
Choose this fix when the data does not need to be regenerated on every request. Move the call into a function and add the [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) directive as the first statement of the function body. The function still runs the underlying query, but Next.js caches the result for the configured lifetime and the surrounding route becomes prerenderable. Choose this fix when the data does not need to be regenerated on every request. Move the call into a function and add the [`use cache`](/docs/app/api-reference/directives/use-cache) directive as the first statement of the function body. The function still runs the underlying query, but Next.js caches the result for the configured lifetime and the surrounding route becomes prerenderable.
This fix does not apply to [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection). The whole point of `connection()` is to opt into per-request rendering for the wrapped subtree, so caching it would defeat the purpose. Use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead. This fix does not apply to [`connection()`](/docs/app/api-reference/functions/connection). The whole point of `connection()` is to opt into per-request rendering for the wrapped subtree, so caching it would defeat the purpose. Use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead.
### Patterns ### Patterns
#### Cache the data-access function #### Cache the data-access function
Move the [`fetch()`](https://preview.nextjs.org/docs/app/getting-started/fetching-data) or database call into its own function and mark that function with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Arguments to the function and closed-over variables become part of the cache key, so prefer passing the values you depend on as arguments to make the contract explicit. Move the [`fetch()`](/docs/app/getting-started/fetching-data) or database call into its own function and mark that function with [`use cache`](/docs/app/api-reference/directives/use-cache). Arguments to the function and closed-over variables become part of the cache key, so prefer passing the values you depend on as arguments to make the contract explicit.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
async function getRecentTransactions(limit) { async function getRecentTransactions(limit) {
...@@ -202,11 +201,11 @@ export default async function Page() { ...@@ -202,11 +201,11 @@ export default async function Page() {
} }
``` ```
Learn more: [Fetching Data](https://preview.nextjs.org/docs/app/getting-started/fetching-data). Learn more: [Fetching Data](/docs/app/getting-started/fetching-data).
#### Cache the whole component #### Cache the whole component
When the component does nothing but read data and render it, mark the [component itself](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache#caching-a-components-output-with-use-cache) with `use cache`. Next.js caches the rendered JSX, which is cheaper to reuse than recomputing it from the cached data. When the component does nothing but read data and render it, mark the [component itself](/docs/app/api-reference/directives/use-cache#caching-a-components-output-with-use-cache) with `use cache`. Next.js caches the rendered JSX, which is cheaper to reuse than recomputing it from the cached data.
```jsx filename="app/dashboard/transaction-list.js" ```jsx filename="app/dashboard/transaction-list.js"
export async function TransactionList({ limit }) { export async function TransactionList({ limit }) {
...@@ -222,11 +221,11 @@ export async function TransactionList({ limit }) { ...@@ -222,11 +221,11 @@ export async function TransactionList({ limit }) {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache#caching-a-components-output-with-use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache#caching-a-components-output-with-use-cache).
#### Tag the cache for targeted invalidation #### Tag the cache for targeted invalidation
Choose this when you want control over when the cached value is refreshed. Tag the entry with [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag) and invalidate it on demand: call [`updateTag`](/docs/app/api-reference/functions/updateTag) from a [Server Action](https://preview.nextjs.org/docs/app/getting-started/mutating-data) when the user performed the mutation and should see fresh data on the next request, or [`revalidateTag`](https://preview.nextjs.org/docs/app/api-reference/functions/revalidateTag) from a route handler, cron, admin tool, or incoming webhook for stale-while-revalidate refreshes. Tags add an on-demand invalidation path on top of the [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) expiration window. The two are independent. Choose this when you want control over when the cached value is refreshed. Tag the entry with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) and invalidate it on demand: call [`updateTag`](/docs/app/api-reference/functions/updateTag) from a [Server Action](/docs/app/getting-started/mutating-data) when the user performed the mutation and should see fresh data on the next request, or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) from a route handler, cron, admin tool, or incoming webhook for stale-while-revalidate refreshes. Tags add an on-demand invalidation path on top of the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) expiration window. The two are independent.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
import { cacheTag } from 'next/cache' import { cacheTag } from 'next/cache'
...@@ -238,11 +237,11 @@ async function getRecentTransactions() { ...@@ -238,11 +237,11 @@ async function getRecentTransactions() {
} }
``` ```
Learn more: [How revalidation works](https://preview.nextjs.org/docs/app/guides/how-revalidation-works). Learn more: [How revalidation works](/docs/app/guides/how-revalidation-works).
#### Set an explicit `cacheLife` profile #### Set an explicit `cacheLife` profile
When the data has a natural shelf-life (hourly metrics, daily aggregates), pick a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile that matches. Without a profile, Next.js uses the project default. When the data has a natural shelf-life (hourly metrics, daily aggregates), pick a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile that matches. Without a profile, Next.js uses the project default.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -254,28 +253,28 @@ async function getDashboard() { ...@@ -254,28 +253,28 @@ async function getDashboard() {
} }
``` ```
Learn more: [How to configure cache lifetimes](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife). Learn more: [How to configure cache lifetimes](/docs/app/api-reference/functions/cacheLife).
### Trade-off ### Trade-off
Freshness becomes a property of the cache configuration, not the data source. The cached response is reused until [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) revalidates or expires, or until [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag) is invalidated. Plan invalidations alongside the code that mutates the data. Call [`updateTag`](/docs/app/api-reference/functions/updateTag) from a [Server Action](https://preview.nextjs.org/docs/app/getting-started/mutating-data) when the user performed the mutation and should see fresh data on the next request, or [`revalidateTag`](https://preview.nextjs.org/docs/app/api-reference/functions/revalidateTag) from a route handler, cron, or webhook for stale-while-revalidate refreshes. Freshness becomes a property of the cache configuration, not the data source. The cached response is reused until [`cacheLife`](/docs/app/api-reference/functions/cacheLife) revalidates or expires, or until [`cacheTag`](/docs/app/api-reference/functions/cacheTag) is invalidated. Plan invalidations alongside the code that mutates the data. Call [`updateTag`](/docs/app/api-reference/functions/updateTag) from a [Server Action](/docs/app/getting-started/mutating-data) when the user performed the mutation and should see fresh data on the next request, or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) from a route handler, cron, or webhook for stale-while-revalidate refreshes.
### Gotchas ### Gotchas
- Variables captured from the surrounding scope are automatically bound as part of the cache key. That keeps cached entries per-value, but it also means a wide closure can balloon the key surface. Prefer passing the dependencies you care about as function arguments so the contract is explicit. - Variables captured from the surrounding scope are automatically bound as part of the cache key. That keeps cached entries per-value, but it also means a wide closure can balloon the key surface. Prefer passing the dependencies you care about as function arguments so the contract is explicit.
- The `"use cache"` directive runs on the server. It can't wrap a function that uses runtime APIs such as [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers). Read those outside the cached scope and pass the values as arguments, or use [`"use cache: private"`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache-private). - The `"use cache"` directive runs on the server. It can't wrap a function that uses runtime APIs such as [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers). Read those outside the cached scope and pass the values as arguments, or use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private).
- If you cache a function and still see this error, the `cacheLife` may be too short to prerender. See [Short-lived caches](#short-lived-caches). - If you cache a function and still see this error, the `cacheLife` may be too short to prerender. See [Short-lived caches](#short-lived-caches).
- The default in-memory cache is per-server-instance. If the upstream call is expensive and you want a shared cache across instances, use [`"use cache: remote"`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache-remote) instead. It trades a network roundtrip for a single cache shared by all servers. - The default in-memory cache is per-server-instance. If the upstream call is expensive and you want a shared cache across instances, use [`"use cache: remote"`](/docs/app/api-reference/directives/use-cache-remote) instead. It trades a network roundtrip for a single cache shared by all servers.
### Short-lived caches ### Short-lived caches
[`"use cache"`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](https://preview.nextjs.org/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming. [`"use cache"`](/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming.
To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead. To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead.
## Allow blocking route ## Allow blocking route
Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes. Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes.
### Patterns ### Patterns
...@@ -292,11 +291,11 @@ export default async function Page() { ...@@ -292,11 +291,11 @@ export default async function Page() {
} }
``` ```
Learn more: [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation). Learn more: [Ensuring instant navigations](/docs/app/guides/instant-navigation).
#### Opt the layout out #### Opt the layout out
When the shared layout itself can't ship instantly (it reads runtime data or uncached data of its own), set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated. When the shared layout itself can't ship instantly (it reads runtime data or uncached data of its own), set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
export const instant = false export const instant = false
...@@ -306,11 +305,11 @@ export default function DashboardLayout({ children }) { ...@@ -306,11 +305,11 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use either pattern when: Use either pattern when:
- The route needs request-time data high in the tree to decide what to render (for example auth, tenant, or other gating in a layout), so there is no meaningful [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) worth showing first. - The route needs request-time data high in the tree to decide what to render (for example auth, tenant, or other gating in a layout), so there is no meaningful [static shell](/docs/app/glossary#static-shell) worth showing first.
- You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today. - You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today.
Don't use this to dismiss the error. Choose [Cache the component or data](#cache-the-component-or-data) or [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when either is feasible. Don't use this to dismiss the error. Choose [Cache the component or data](#cache-the-component-or-data) or [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when either is feasible.
...@@ -321,23 +320,23 @@ Navigations to this route are not instant. The user waits for the full server re ...@@ -321,23 +320,23 @@ Navigations to this route are not instant. The user waits for the full server re
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- This export does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route. - This export does not disable [prerendering](/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,15 +17,14 @@ kind: insight ...@@ -17,15 +17,14 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), [`generateMetadata()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata) performed an uncached data access ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database call, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection)). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js expects metadata to be prerenderable when the rest of the route is. This route's metadata is blocked, but the rest of its content can be prerendered. During [prerendering](/docs/app/glossary#prerendering), [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata) performed an uncached data access ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database call, [`await connection()`](/docs/app/api-reference/functions/connection)). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js expects metadata to be prerenderable when the rest of the route is. This route's metadata is blocked, but the rest of its content can be prerendered.
Request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)) in `generateMetadata()` have different fixes. See [Next.js encountered runtime data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-runtime). Request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)) in `generateMetadata()` have different fixes. See [Next.js encountered runtime data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-runtime).
The viewport equivalent is handled at [Uncached data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-dynamic). The viewport equivalent is handled at [Uncached data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-dynamic).
...@@ -57,9 +56,9 @@ For errors in the page body rather than metadata, see [Next.js encountered uncac ...@@ -57,9 +56,9 @@ For errors in the page body rather than metadata, see [Next.js encountered uncac
## Cache the metadata ## Cache the metadata
Choose this fix when the metadata comes from an external source (CMS, database) but doesn't need to change on every request. Add the [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) directive as the first statement inside [`generateMetadata()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata). Next.js caches the returned metadata object and includes it in the prerender. Choose this fix when the metadata comes from an external source (CMS, database) but doesn't need to change on every request. Add the [`use cache`](/docs/app/api-reference/directives/use-cache) directive as the first statement inside [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata). Next.js caches the returned metadata object and includes it in the prerender.
This fix does not apply to [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection). The point of `connection()` is to opt into per-request rendering, so caching it would defeat the purpose. Use [Mark the route as dynamic](#mark-the-route-as-dynamic) instead. This fix does not apply to [`connection()`](/docs/app/api-reference/functions/connection). The point of `connection()` is to opt into per-request rendering, so caching it would defeat the purpose. Use [Mark the route as dynamic](#mark-the-route-as-dynamic) instead.
### Patterns ### Patterns
...@@ -90,11 +89,11 @@ export default async function Page({ params }) { ...@@ -90,11 +89,11 @@ export default async function Page({ params }) {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache).
#### Tag the metadata for invalidation #### Tag the metadata for invalidation
When you publish new content and want the metadata to refresh, tag the entry with [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag). Invalidate from a Server Action with [`updateTag`](/docs/app/api-reference/functions/updateTag) (read-your-own-writes: the next request waits for fresh data) or from a Route Handler with [`revalidateTag`](https://preview.nextjs.org/docs/app/api-reference/functions/revalidateTag). When you publish new content and want the metadata to refresh, tag the entry with [`cacheTag`](/docs/app/api-reference/functions/cacheTag). Invalidate from a Server Action with [`updateTag`](/docs/app/api-reference/functions/updateTag) (read-your-own-writes: the next request waits for fresh data) or from a Route Handler with [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag).
```jsx filename="app/blog/[slug]/page.js" ```jsx filename="app/blog/[slug]/page.js"
import { cacheTag } from 'next/cache' import { cacheTag } from 'next/cache'
...@@ -109,21 +108,21 @@ export async function generateMetadata({ params }) { ...@@ -109,21 +108,21 @@ export async function generateMetadata({ params }) {
} }
``` ```
Learn more: [How revalidation works](https://preview.nextjs.org/docs/app/guides/how-revalidation-works). Learn more: [How revalidation works](/docs/app/guides/how-revalidation-works).
### Trade-off ### Trade-off
Freshness depends on the cache configuration. The metadata stays the same until [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) revalidates or expires, or until [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag) is invalidated. Plan invalidations alongside the code that mutates the content. Freshness depends on the cache configuration. The metadata stays the same until [`cacheLife`](/docs/app/api-reference/functions/cacheLife) revalidates or expires, or until [`cacheTag`](/docs/app/api-reference/functions/cacheTag) is invalidated. Plan invalidations alongside the code that mutates the content.
### Gotchas ### Gotchas
- [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) can't be combined with [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) in the same scope. Inside a cached function, you can't call request-bound APIs. If the metadata needs a request-bound value (a session token to call a protected API), read it outside the cached scope and pass it as an argument, or use [Mark the route as dynamic](#mark-the-route-as-dynamic) instead. - [`use cache`](/docs/app/api-reference/directives/use-cache) can't be combined with [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) in the same scope. Inside a cached function, you can't call request-bound APIs. If the metadata needs a request-bound value (a session token to call a protected API), read it outside the cached scope and pass it as an argument, or use [Mark the route as dynamic](#mark-the-route-as-dynamic) instead.
- If the metadata function reads `params`, the params become part of the cache key automatically. Each unique param set gets its own cached metadata entry. - If the metadata function reads `params`, the params become part of the cache key automatically. Each unique param set gets its own cached metadata entry.
- A short [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) (a profile whose `revalidate` is shorter than the prerender's effective lifetime) prevents the metadata from being included in the prerender. The route becomes partially dynamic. Use a longer profile if you want the metadata included in the static shell. - A short [`cacheLife`](/docs/app/api-reference/functions/cacheLife) (a profile whose `revalidate` is shorter than the prerender's effective lifetime) prevents the metadata from being included in the prerender. The route becomes partially dynamic. Use a longer profile if you want the metadata included in the static shell.
## Mark the route as dynamic ## Mark the route as dynamic
Choose this fix when the rest of the page is fully static and you want the metadata to remain dynamic. Add a small component that calls [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), render `null` from it, and wrap it in [`<Suspense>`](https://react.dev/reference/react/Suspense). Choose this fix when the rest of the page is fully static and you want the metadata to remain dynamic. Add a small component that calls [`await connection()`](/docs/app/api-reference/functions/connection), render `null` from it, and wrap it in [`<Suspense>`](https://react.dev/reference/react/Suspense).
This error fires specifically because the metadata is the only dynamic part of an otherwise fully prerenderable route. Adding a dynamic marker is an explicit signal to Next.js that the page has intentional dynamic content streamed alongside the static shell, so the dynamic metadata is allowed. This error fires specifically because the metadata is the only dynamic part of an otherwise fully prerenderable route. Adding a dynamic marker is an explicit signal to Next.js that the page has intentional dynamic content streamed alongside the static shell, so the dynamic metadata is allowed.
...@@ -131,7 +130,7 @@ This error fires specifically because the metadata is the only dynamic part of a ...@@ -131,7 +130,7 @@ This error fires specifically because the metadata is the only dynamic part of a
#### Add a dynamic marker component #### Add a dynamic marker component
Create a small component that calls [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) and renders nothing, wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The page content remains prerenderable and only the marker is excluded from the prerender. Create a small component that calls [`connection()`](/docs/app/api-reference/functions/connection) and renders nothing, wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The page content remains prerenderable and only the marker is excluded from the prerender.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -160,7 +159,7 @@ export default function Page() { ...@@ -160,7 +159,7 @@ export default function Page() {
} }
``` ```
Learn more: [`connection`](https://preview.nextjs.org/docs/app/api-reference/functions/connection). Learn more: [`connection`](/docs/app/api-reference/functions/connection).
### Trade-off ### Trade-off
...@@ -170,23 +169,23 @@ The metadata and the dynamic marker run on every request, so the route cannot be ...@@ -170,23 +169,23 @@ The metadata and the dynamic marker run on every request, so the route cannot be
- The `DynamicMarker` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). Without the boundary, the dynamic marker propagates up and the entire page is treated as blocking, surfacing the same blocking-route error this fix is meant to address. - The `DynamicMarker` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). Without the boundary, the dynamic marker propagates up and the entire page is treated as blocking, surfacing the same blocking-route error this fix is meant to address.
- This pattern is intentionally verbose. If you find yourself adding a dynamic marker, reconsider whether the metadata can be cached instead. Most metadata doesn't need to be per-request. - This pattern is intentionally verbose. If you find yourself adding a dynamic marker, reconsider whether the metadata can be cached instead. Most metadata doesn't need to be per-request.
- If the page already has a genuinely dynamic component (one that reads [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or uncached data inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary), you won't see this error. The page is already partially dynamic. - If the page already has a genuinely dynamic component (one that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or uncached data inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary), you won't see this error. The page is already partially dynamic.
- Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateMetadata` and must be statically prerendered. The dynamic marker doesn't help here, because these routes don't have a page body where you can place a Suspense'd marker. If your root layout's `generateMetadata` depends on uncached data, [Cache the metadata](#cache-the-metadata) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateMetadata`. - Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateMetadata` and must be statically prerendered. The dynamic marker doesn't help here, because these routes don't have a page body where you can place a Suspense'd marker. If your root layout's `generateMetadata` depends on uncached data, [Cache the metadata](#cache-the-metadata) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateMetadata`.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,15 +17,14 @@ kind: insight ...@@ -17,15 +17,14 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), [`generateMetadata()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata) or file-based metadata read a per-request value ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js expects metadata to be prerenderable when the rest of the route is. This route's metadata is blocked, but the rest of its content can be prerendered. During [prerendering](/docs/app/glossary#prerendering), [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata) or file-based metadata read a per-request value ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js expects metadata to be prerenderable when the rest of the route is. This route's metadata is blocked, but the rest of its content can be prerendered.
Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection)) in `generateMetadata()` have different fixes. See [Next.js encountered uncached data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-dynamic). Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](/docs/app/api-reference/functions/connection)) in `generateMetadata()` have different fixes. See [Next.js encountered uncached data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-dynamic).
The viewport equivalent is handled at [Runtime data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-runtime). The viewport equivalent is handled at [Runtime data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-runtime).
...@@ -57,7 +56,7 @@ For errors in the page body rather than metadata, see [Next.js encountered runti ...@@ -57,7 +56,7 @@ For errors in the page body rather than metadata, see [Next.js encountered runti
## Use static metadata ## Use static metadata
Choose this fix when the metadata values are known at build time and don't change per request. Replace [`generateMetadata()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata) with a static [`metadata`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata#metadata-object) export. The metadata is evaluated once during the build and included in every prerender. Choose this fix when the metadata values are known at build time and don't change per request. Replace [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata) with a static [`metadata`](/docs/app/api-reference/functions/generate-metadata#metadata-object) export. The metadata is evaluated once during the build and included in every prerender.
### Patterns ### Patterns
...@@ -76,11 +75,11 @@ export default function Page() { ...@@ -76,11 +75,11 @@ export default function Page() {
} }
``` ```
Learn more: [Static metadata](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata#metadata-object). Learn more: [Static metadata](/docs/app/api-reference/functions/generate-metadata#metadata-object).
#### Use `generateStaticParams` for per-param metadata #### Use `generateStaticParams` for per-param metadata
When metadata varies by route param (a blog post title, a product name), pair [`generateStaticParams`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-static-params) with [`generateMetadata`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata). Each param set is prerendered with its own metadata at build time. When metadata varies by route param (a blog post title, a product name), pair [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) with [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata). Each param set is prerendered with its own metadata at build time.
```jsx filename="app/blog/[slug]/page.js" ```jsx filename="app/blog/[slug]/page.js"
export function generateStaticParams() { export function generateStaticParams() {
...@@ -95,7 +94,7 @@ export async function generateMetadata({ params }) { ...@@ -95,7 +94,7 @@ export async function generateMetadata({ params }) {
} }
``` ```
Learn more: [`generateStaticParams`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-static-params). Learn more: [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params).
### Trade-off ### Trade-off
...@@ -103,12 +102,12 @@ Static metadata can't reflect per-request values like the visitor's locale, A/B ...@@ -103,12 +102,12 @@ Static metadata can't reflect per-request values like the visitor's locale, A/B
### Gotchas ### Gotchas
- File-based metadata (e.g. an [`icon.js`](/docs/app/api-reference/file-conventions/metadata/app-icons) or [`opengraph-image.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image) inside a dynamic segment) implicitly depends on `params`. If the segment is dynamic, Next.js treats the metadata function as dynamic too. Pair with [`generateStaticParams`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-static-params) or switch to a static file (e.g. `icon.png`). - File-based metadata (e.g. an [`icon.js`](/docs/app/api-reference/file-conventions/metadata/app-icons) or [`opengraph-image.js`](/docs/app/api-reference/file-conventions/metadata/opengraph-image) inside a dynamic segment) implicitly depends on `params`. If the segment is dynamic, Next.js treats the metadata function as dynamic too. Pair with [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) or switch to a static file (e.g. `icon.png`).
- A [`template`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-metadata#template) in a parent layout's metadata applies at build time. It doesn't introduce a dynamic dependency. - A [`template`](/docs/app/api-reference/functions/generate-metadata#template) in a parent layout's metadata applies at build time. It doesn't introduce a dynamic dependency.
## Mark the route as dynamic ## Mark the route as dynamic
Choose this fix when the metadata genuinely requires per-request data (a personalized title from a protected API, a theme color from a cookie) and a static export isn't feasible. Add a small component that calls [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), render `null` from it, and wrap it in [`<Suspense>`](https://react.dev/reference/react/Suspense). Choose this fix when the metadata genuinely requires per-request data (a personalized title from a protected API, a theme color from a cookie) and a static export isn't feasible. Add a small component that calls [`await connection()`](/docs/app/api-reference/functions/connection), render `null` from it, and wrap it in [`<Suspense>`](https://react.dev/reference/react/Suspense).
This error fires specifically because the metadata is the only dynamic part of an otherwise fully prerenderable route. Adding a dynamic marker is an explicit signal to Next.js that the page has intentional dynamic content streamed alongside the static shell, so the dynamic metadata is allowed. This error fires specifically because the metadata is the only dynamic part of an otherwise fully prerenderable route. Adding a dynamic marker is an explicit signal to Next.js that the page has intentional dynamic content streamed alongside the static shell, so the dynamic metadata is allowed.
...@@ -116,7 +115,7 @@ This error fires specifically because the metadata is the only dynamic part of a ...@@ -116,7 +115,7 @@ This error fires specifically because the metadata is the only dynamic part of a
#### Add a dynamic marker component #### Add a dynamic marker component
Create a small component that calls [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) and renders nothing, wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The page content remains prerenderable and only the marker is excluded from the prerender. Create a small component that calls [`connection()`](/docs/app/api-reference/functions/connection) and renders nothing, wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The page content remains prerenderable and only the marker is excluded from the prerender.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -149,7 +148,7 @@ export default function Page() { ...@@ -149,7 +148,7 @@ export default function Page() {
} }
``` ```
Learn more: [`connection`](https://preview.nextjs.org/docs/app/api-reference/functions/connection). Learn more: [`connection`](/docs/app/api-reference/functions/connection).
### Trade-off ### Trade-off
...@@ -159,23 +158,23 @@ The metadata and the dynamic marker run on every request, so the route cannot be ...@@ -159,23 +158,23 @@ The metadata and the dynamic marker run on every request, so the route cannot be
- The `DynamicMarker` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). Without the boundary, the dynamic marker propagates up and the entire page is treated as blocking, surfacing the same blocking-route error this fix is meant to address. - The `DynamicMarker` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). Without the boundary, the dynamic marker propagates up and the entire page is treated as blocking, surfacing the same blocking-route error this fix is meant to address.
- This pattern is intentionally verbose. If you find yourself adding a dynamic marker, reconsider whether the metadata can be cached instead. Most metadata doesn't need to be per-request. - This pattern is intentionally verbose. If you find yourself adding a dynamic marker, reconsider whether the metadata can be cached instead. Most metadata doesn't need to be per-request.
- If the page already has a genuinely dynamic component (one that reads [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary), you won't see this error. The page is already partially dynamic. - If the page already has a genuinely dynamic component (one that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary), you won't see this error. The page is already partially dynamic.
- Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateMetadata` and must be statically prerendered. The dynamic marker doesn't help here, because these routes don't have a page body where you can place a Suspense'd marker. If your root layout's `generateMetadata` depends on request data, [Use static metadata](#use-static-metadata) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateMetadata`. - Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateMetadata` and must be statically prerendered. The dynamic marker doesn't help here, because these routes don't have a page body where you can place a Suspense'd marker. If your root layout's `generateMetadata` depends on request data, [Use static metadata](#use-static-metadata) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateMetadata`.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,10 +17,9 @@ kind: insight ...@@ -17,10 +17,9 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake an unpredictable value into the prerendered HTML. The SSR value won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client. A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake an unpredictable value into the prerendered HTML. The SSR value won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client.
...@@ -86,15 +85,15 @@ export function Avatar() { ...@@ -86,15 +85,15 @@ export function Avatar() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Use [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading) for full-segment fallback or pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible. Use [`loading.js`](/docs/app/api-reference/file-conventions/loading) for full-segment fallback or pick a fallback that matches the final layout so it doesn't cause a layout shift when the component hydrates. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) in any of them raises this same error. Use stable placeholder content. - Any UI rendered as part of the prerender shell must be deterministic, including [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) in any of them raises this same error. Use stable placeholder content.
- The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the random value only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead. - The inner Client Component still runs during SSR, behind the boundary. If you need to guarantee the random value only runs in the browser, use [Move into effect or event handler](#move-into-effect-or-event-handler) instead.
- A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) re-renders on the client (a parent state change, a context update), it produces a new value each time. To stabilize the value across re-renders, call [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop. - A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary only fixes the prerender/hydration mismatch, not client re-renders. If the component using [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) re-renders on the client (a parent state change, a context update), it produces a new value each time. To stabilize the value across re-renders, call [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) once in a [`useState`](https://react.dev/reference/react/useState) initializer or [`useRef`](https://react.dev/reference/react/useRef), or compute it on the server and pass it down as a prop.
...@@ -181,7 +180,7 @@ Learn more: [`useRef`](https://react.dev/reference/react/useRef). ...@@ -181,7 +180,7 @@ Learn more: [`useRef`](https://react.dev/reference/react/useRef).
### Trade-off ### Trade-off
The user sees the placeholder briefly before the real value. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The user sees the placeholder briefly before the real value. For interactions the wait is invisible, but for `useEffect`-based values there's a flash of the initial state. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -194,7 +193,7 @@ The user sees the placeholder briefly before the real value. For interactions th ...@@ -194,7 +193,7 @@ The user sees the placeholder briefly before the real value. For interactions th
### Suspend with `use(io())` ### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/random-banner.js" ```jsx filename="app/components/random-banner.js"
'use client' 'use client'
...@@ -222,17 +221,17 @@ export default function Page() { ...@@ -222,17 +221,17 @@ export default function Page() {
} }
``` ```
Learn more: [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io). Learn more: [`io`](/docs/app/api-reference/functions/io).
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,13 +17,12 @@ kind: insight ...@@ -17,13 +17,12 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a Server Component called [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake an unpredictable value into the prerendered HTML. The value at build time will differ from the value at runtime, so you need to choose: cache the value so it's stable, defer the call behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client. During [prerendering](/docs/app/glossary#prerendering), a Server Component called [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't bake an unpredictable value into the prerendered HTML. The value at build time will differ from the value at runtime, so you need to choose: cache the value so it's stable, defer the call behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so it runs per-request, or move it to the client.
Other unpredictable APIs ([`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: see [`Date.now()`](/docs/messages/blocking-prerender-current-time) and [crypto APIs](/docs/messages/blocking-prerender-crypto). The Client Component case is handled at [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client). Other unpredictable APIs ([`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: see [`Date.now()`](/docs/messages/blocking-prerender-current-time) and [crypto APIs](/docs/messages/blocking-prerender-crypto). The Client Component case is handled at [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client).
...@@ -64,13 +63,13 @@ Other unpredictable APIs ([`Date.now()`](https://developer.mozilla.org/en-US/doc ...@@ -64,13 +63,13 @@ Other unpredictable APIs ([`Date.now()`](https://developer.mozilla.org/en-US/doc
## Generate on every request ## Generate on every request
Choose this fix when each request genuinely needs a different value. A [unique session ID](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), a single-use nonce, an A/B test bucket: anything that has to be fresh per visitor. Add [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request. Choose this fix when each request genuinely needs a different value. A [unique session ID](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), a single-use nonce, an A/B test bucket: anything that has to be fresh per visitor. Add [`await connection()`](/docs/app/api-reference/functions/connection) before the call to tell Next.js the surrounding component is request-bound. The component is excluded from the prerender and streamed in from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary on each request.
### Patterns ### Patterns
#### Use `await connection()` before the random call #### Use `await connection()` before the random call
Call [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection) before [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random). Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in. Call [`connection()`](/docs/app/api-reference/functions/connection) before [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random). Everything after the `await` is request-time. Wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the surrounding shell stays prerendered and only the dynamic part streams in.
Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the random read as possible. If the parent has cached content (a header, stats, navigation), isolate the random read in its own component so only that piece falls behind the boundary. Push the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary as close to the random read as possible. If the parent has cached content (a header, stats, navigation), isolate the random read in its own component so only that piece falls behind the boundary.
...@@ -101,7 +100,7 @@ export async function RequestTrace() { ...@@ -101,7 +100,7 @@ export async function RequestTrace() {
#### Alternative: `await io()` #### Alternative: `await io()`
Use [`io()`](https://preview.nextjs.org/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/request-trace.js" ```jsx filename="app/dashboard/request-trace.js"
import { io } from 'next/cache' import { io } from 'next/cache'
...@@ -113,27 +112,27 @@ export async function RequestTrace() { ...@@ -113,27 +112,27 @@ export async function RequestTrace() {
} }
``` ```
Learn more: [`connection`](https://preview.nextjs.org/docs/app/api-reference/functions/connection), [`io`](https://preview.nextjs.org/docs/app/api-reference/functions/io), [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [`connection`](/docs/app/api-reference/functions/connection), [`io`](/docs/app/api-reference/functions/io), [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it can paint. Make sure the fallback approximates the final layout so it doesn't cause a layout shift when the value arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The route renders on every request. The shell still ships instantly because of the [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, but the dynamic region waits on the server render before it can paint. Make sure the fallback approximates the final layout so it doesn't cause a layout shift when the value arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading), [`error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/error#global-error). Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error. - Any UI rendered as part of the prerender shell must be deterministic. That includes [`<Suspense>`](https://react.dev/reference/react/Suspense) fallbacks, [`loading.js`](/docs/app/api-reference/file-conventions/loading), [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`global-error.js`](/docs/app/api-reference/file-conventions/error#global-error). Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) in any of them raises this same error.
- If [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) is being used as a unique ID for logging or correlation, consider an incrementing integer or [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) request scope. Those don't trigger the error at all because they aren't unpredictable from Next.js's point of view. - If [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) is being used as a unique ID for logging or correlation, consider an incrementing integer or [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) request scope. Those don't trigger the error at all because they aren't unpredictable from Next.js's point of view.
- Random values produced inside third-party packages will surface this error in your project code. The same fixes apply at the call site that consumes the value. - Random values produced inside third-party packages will surface this error in your project code. The same fixes apply at the call site that consumes the value.
## Cache the random value ## Cache the random value
Choose this fix when one stable random value per build, deployment, or `cacheLife` window is acceptable. The classic case is a daily shuffle of items where the same shuffle is fine for every visitor that day. Move the [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) call into a function with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) as the first statement. Next.js evaluates the function once per cache key and reuses the result. Choose this fix when one stable random value per build, deployment, or `cacheLife` window is acceptable. The classic case is a daily shuffle of items where the same shuffle is fine for every visitor that day. Move the [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) call into a function with [`use cache`](/docs/app/api-reference/directives/use-cache) as the first statement. Next.js evaluates the function once per cache key and reuses the result.
### Patterns ### Patterns
#### Cache the producer function #### Cache the producer function
Wrap the random generation in its own function with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). The returned value is part of the cache entry, so every consumer sees the same random number until the cache is invalidated. Wrap the random generation in its own function with [`use cache`](/docs/app/api-reference/directives/use-cache). The returned value is part of the cache entry, so every consumer sees the same random number until the cache is invalidated.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
async function getRandomSeed() { async function getRandomSeed() {
...@@ -148,11 +147,11 @@ export default async function Page() { ...@@ -148,11 +147,11 @@ export default async function Page() {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache).
#### Control the rotation window with `cacheLife` #### Control the rotation window with `cacheLife`
When you want the random value to rotate on a schedule (a daily featured item, an hourly shuffle), set a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. When you want the random value to rotate on a schedule (a daily featured item, an hourly shuffle), set a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile.
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -164,7 +163,7 @@ async function getDailySeed() { ...@@ -164,7 +163,7 @@ async function getDailySeed() {
} }
``` ```
Learn more: [How to configure cache lifetimes](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife). Learn more: [How to configure cache lifetimes](/docs/app/api-reference/functions/cacheLife).
### Trade-off ### Trade-off
...@@ -172,13 +171,13 @@ Every visitor in the cache window sees the same "random" value. That's the right ...@@ -172,13 +171,13 @@ Every visitor in the cache window sees the same "random" value. That's the right
### Gotchas ### Gotchas
- Inside a [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) scope, you can't call [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), which means you can't key the random value by request identity. - Inside a [`use cache`](/docs/app/api-reference/directives/use-cache) scope, you can't call [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), which means you can't key the random value by request identity.
- If the same random value is used in many places, hoist the cached function up so all consumers share the cache entry instead of producing a different cached value at each call site. - If the same random value is used in many places, hoist the cached function up so all consumers share the cache entry instead of producing a different cached value at each call site.
- If you cache a function and still see this error, the [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches). - If you cache a function and still see this error, the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) may be too short to prerender. See [Short-lived caches](#short-lived-caches).
### Short-lived caches ### Short-lived caches
[`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](https://preview.nextjs.org/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming. [`use cache`](/docs/app/api-reference/directives/use-cache) accepts a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile. A short profile (such as `"seconds"` or `"minutes"`) whose `revalidate` is shorter than the prerender's effective lifetime prevents the value from being included in the prerender. The segment becomes a dynamic hole instead. The cache entry still helps the [Client Cache](/docs/app/glossary#client-cache) and protects upstream APIs, but the page falls back to streaming.
To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead. To keep the page prerendered, use a profile with a longer revalidate window such as `"default"` (15 minutes), `"hours"`, or `"days"`. If a short profile is intentional, treat the value as dynamic and use [Generate on every request](#generate-on-every-request) instead.
...@@ -219,7 +218,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp ...@@ -219,7 +218,7 @@ Learn more: [Client Components](/docs/app/getting-started/server-and-client-comp
### Trade-off ### Trade-off
The first paint shows the SSR fallback or initial state, and the random value appears only after the browser hydrates the component. That's fine for UI flourishes but wrong for content that has to be in the prerendered HTML. See [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash. The first paint shows the SSR fallback or initial state, and the random value appears only after the browser hydrates the component. That's fine for UI flourishes but wrong for content that has to be in the prerendered HTML. See [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for techniques that eliminate the flash.
### Gotchas ### Gotchas
...@@ -229,11 +228,11 @@ The first paint shows the SSR fallback or initial state, and the random value ap ...@@ -229,11 +228,11 @@ The first paint shows the SSR fallback or initial state, and the random value ap
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
## Related Insights ## Related Insights
......
...@@ -17,17 +17,16 @@ kind: insight ...@@ -17,17 +17,16 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), or [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional) was read outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't prerender any part of the tree that depends on a per-request value, so navigations to this route block instead of being [instant](https://preview.nextjs.org/docs/app/guides/instant-navigation). During [prerendering](/docs/app/glossary#prerendering), [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), or [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) was read outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js can't prerender any part of the tree that depends on a per-request value, so navigations to this route block instead of being [instant](/docs/app/guides/instant-navigation).
Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection)) have different fixes. See [Next.js encountered uncached data during prerendering](/docs/messages/blocking-prerender-dynamic). Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](/docs/app/api-reference/functions/connection)) have different fixes. See [Next.js encountered uncached data during prerendering](/docs/messages/blocking-prerender-dynamic).
This error can also appear during a client-side navigation when the data access sits inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary from a parent layout but that boundary is too high. It wraps the entire segment instead of only the dynamic part, so the navigation still blocks. Push the boundary closer to the data access so the rest of the segment stays in the [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell). See [Choosing where to place the boundary](#choosing-where-to-place-the-boundary). This error can also appear during a client-side navigation when the data access sits inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary from a parent layout but that boundary is too high. It wraps the entire segment instead of only the dynamic part, so the navigation still blocks. Push the boundary closer to the data access so the rest of the segment stays in the [static shell](/docs/app/glossary#static-shell). See [Choosing where to place the boundary](#choosing-where-to-place-the-boundary).
## Ways to fix this ## Ways to fix this
...@@ -55,7 +54,7 @@ This error can also appear during a client-side navigation when the data access ...@@ -55,7 +54,7 @@ This error can also appear during a client-side navigation when the data access
## Wrap in or move into Suspense ## Wrap in or move into Suspense
Choose this fix when the value really is per-request, but the page has parts that don't depend on it. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary lets the static shell ship instantly while the dynamic region [streams](https://preview.nextjs.org/docs/app/glossary#streaming) in once the request value resolves. Choose this fix when the value really is per-request, but the page has parts that don't depend on it. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary lets the static shell ship instantly while the dynamic region [streams](/docs/app/glossary#streaming) in once the request value resolves.
### Patterns ### Patterns
...@@ -80,7 +79,7 @@ export default function Page() { ...@@ -80,7 +79,7 @@ export default function Page() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
#### Push the access down to the leaf #### Push the access down to the leaf
...@@ -110,7 +109,7 @@ export async function UserHeader() { ...@@ -110,7 +109,7 @@ export async function UserHeader() {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
#### Pass `searchParams` without awaiting #### Pass `searchParams` without awaiting
...@@ -140,11 +139,11 @@ export async function Results({ searchParams }) { ...@@ -140,11 +139,11 @@ export async function Results({ searchParams }) {
} }
``` ```
Learn more: [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional). Learn more: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional).
#### Forward `searchParams` as a promise chain #### Forward `searchParams` as a promise chain
A variant of the previous pattern when you want to derive a value without awaiting at the top. Treat [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional) as a promise and `.then()` it to project the shape the child needs. A variant of the previous pattern when you want to derive a value without awaiting at the top. Treat [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) as a promise and `.then()` it to project the shape the child needs.
```jsx filename="app/dashboard/map/page.js" ```jsx filename="app/dashboard/map/page.js"
export default function Page({ searchParams }) { export default function Page({ searchParams }) {
...@@ -156,11 +155,11 @@ export default function Page({ searchParams }) { ...@@ -156,11 +155,11 @@ export default function Page({ searchParams }) {
} }
``` ```
Learn more: [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional). Learn more: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional).
#### Use `loading.js` for the whole segment #### Use `loading.js` for the whole segment
When every component in the segment reads the same request value and there's nothing static to render above it, a [`loading.js`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading) file in the segment is the shorthand. Next.js wraps `{children}` of the layout in `<Suspense>` automatically. When every component in the segment reads the same request value and there's nothing static to render above it, a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file in the segment is the shorthand. Next.js wraps `{children}` of the layout in `<Suspense>` automatically.
```jsx filename="app/dashboard/loading.js" ```jsx filename="app/dashboard/loading.js"
export default function Loading() { export default function Loading() {
...@@ -170,11 +169,11 @@ export default function Loading() { ...@@ -170,11 +169,11 @@ export default function Loading() {
> **Good to know**: A `loading.js` file wraps the segment's `{children}` in one Suspense boundary. Parent layouts above it still prerender, but everything inside the segment sits behind the fallback. If page-level content could be prerendered (a static intro, a known title), use explicit `<Suspense>` boundaries inside `page.js` around only the dynamic parts. > **Good to know**: A `loading.js` file wraps the segment's `{children}` in one Suspense boundary. Parent layouts above it still prerender, but everything inside the segment sits behind the fallback. If page-level content could be prerendered (a static intro, a known title), use explicit `<Suspense>` boundaries inside `page.js` around only the dynamic parts.
Learn more: [`loading.js` and instant loading states](https://preview.nextjs.org/docs/app/api-reference/file-conventions/loading). Learn more: [`loading.js` and instant loading states](/docs/app/api-reference/file-conventions/loading).
### Trade-off ### Trade-off
The shell ships immediately, but the user sees a loading state for the streamed region on every request. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The shell ships immediately, but the user sees a loading state for the streamed region on every request. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Choosing where to place the boundary ### Choosing where to place the boundary
...@@ -183,21 +182,21 @@ The location of the boundary controls what the user sees during the navigation: ...@@ -183,21 +182,21 @@ The location of the boundary controls what the user sees during the navigation:
- A high boundary (around the whole page) gives one loading state for everything. Less work to set up, but the user loses context about where they were going. - A high boundary (around the whole page) gives one loading state for everything. Less work to set up, but the user loses context about where they were going.
- A low boundary (around the specific component that reads the runtime API) keeps surrounding content visible and only shows a fallback for the per-request part. Preferred when the surrounding shell has cached content. - A low boundary (around the specific component that reads the runtime API) keeps surrounding content visible and only shows a fallback for the per-request part. Preferred when the surrounding shell has cached content.
A useful rule: **push the boundary as low as possible** while keeping the fallback meaningful. The cached content above the boundary becomes part of the [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) on navigation. Wrapping individual pieces or wrapping the whole page in one boundary stream the same way, but a lower boundary keeps more prerendered content visible during the navigation. See [Maximizing the static shell](https://preview.nextjs.org/docs/app/getting-started/caching#streaming-uncached-data) for the canonical pattern. A useful rule: **push the boundary as low as possible** while keeping the fallback meaningful. The cached content above the boundary becomes part of the [static shell](/docs/app/glossary#static-shell) on navigation. Wrapping individual pieces or wrapping the whole page in one boundary stream the same way, but a lower boundary keeps more prerendered content visible during the navigation. See [Maximizing the static shell](/docs/app/getting-started/caching#streaming-uncached-data) for the canonical pattern.
### Gotchas ### Gotchas
- The fallback must be deterministic. Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) inside the fallback raises a separate [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering. - The fallback must be deterministic. Calling [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) or [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) inside the fallback raises a separate [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) error during prerendering.
- Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`. - Do not pass `{children}` through in the fallback. Child pages may include dynamic reads (for example, `/_not-found` calling [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers)) that propagate into what should be a static fallback. Render a placeholder that doesn't include `{children}`.
- If the failing route is `/_not-found` and you don't have a `not-found.tsx` file, the read is in the root layout. `/_not-found` is a real prerendered route that inherits the root layout, so a `cookies()` or `headers()` read there fails on the synthetic route too. Run `next build --debug-prerender` to confirm the originating file, and fix it at the layout, not by adding a `not-found.tsx`. - If the failing route is `/_not-found` and you don't have a `not-found.tsx` file, the read is in the root layout. `/_not-found` is a real prerendered route that inherits the root layout, so a `cookies()` or `headers()` read there fails on the synthetic route too. Run `next build --debug-prerender` to confirm the originating file, and fix it at the layout, not by adding a `not-found.tsx`.
- Boundary placement affects client navigations between sibling routes differently than initial page loads. Validation surfaces this in the dev server and at build time. See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. - Boundary placement affects client navigations between sibling routes differently than initial page loads. Validation surfaces this in the dev server and at build time. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
- The function returned by [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) and [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) is async. Make sure the component reading them is async too, and `await` the call. - The function returned by [`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers) is async. Make sure the component reading them is async too, and `await` the call.
- The `params` and `searchParams` props are also async promises. Treat them like any other awaited value when deciding where the boundary goes. - The `params` and `searchParams` props are also async promises. Treat them like any other awaited value when deciding where the boundary goes.
- Root-element attributes (`<html lang>`, `<html dir>`, `<html data-theme>`) can't be wrapped in `<Suspense>`. You can't suspend the document root, and a boundary inside `<html>` still leaves the attribute itself server-cookie-dependent. Move the read to a pre-paint client script per [Preventing flash before hydration](https://preview.nextjs.org/docs/app/guides/preventing-flash-before-hydration) and add `suppressHydrationWarning` on `<html>` so React doesn't flag the script's mutation as a mismatch. - Root-element attributes (`<html lang>`, `<html dir>`, `<html data-theme>`) can't be wrapped in `<Suspense>`. You can't suspend the document root, and a boundary inside `<html>` still leaves the attribute itself server-cookie-dependent. Move the read to a pre-paint client script per [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) and add `suppressHydrationWarning` on `<html>` so React doesn't flag the script's mutation as a mismatch.
## Allow blocking route ## Allow blocking route
Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes. Choose this fix when the route renders per-request and there's no useful static shell. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes.
### Patterns ### Patterns
...@@ -214,11 +213,11 @@ export default async function Page() { ...@@ -214,11 +213,11 @@ export default async function Page() {
} }
``` ```
Learn more: [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation). Learn more: [Ensuring instant navigations](/docs/app/guides/instant-navigation).
#### Opt the layout out #### Opt the layout out
When the shared layout itself can't ship instantly (it reads [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) of its own), set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated. When the shared layout itself can't ship instantly (it reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) of its own), set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
export const instant = false export const instant = false
...@@ -228,11 +227,11 @@ export default function DashboardLayout({ children }) { ...@@ -228,11 +227,11 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use either pattern when: Use either pattern when:
- The route needs request-time data high in the tree to decide what to render (for example auth, tenant, or other gating in a layout), so there is no meaningful [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) worth showing first. - The route needs request-time data high in the tree to decide what to render (for example auth, tenant, or other gating in a layout), so there is no meaningful [static shell](/docs/app/glossary#static-shell) worth showing first.
- You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today. - You're migrating a route incrementally and want to defer the lifetime decision without changing how the page renders today.
Don't use this to dismiss the error. Choose [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when feasible. Don't use this to dismiss the error. Choose [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when feasible.
...@@ -243,23 +242,23 @@ Navigations to this route are not instant. The user waits for the full server re ...@@ -243,23 +242,23 @@ Navigations to this route are not instant. The user waits for the full server re
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- This export does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route. - This export does not disable [prerendering](/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,15 +17,14 @@ kind: insight ...@@ -17,15 +17,14 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), [`generateViewport()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport) performed an uncached data access ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database call, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection)). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, viewport metadata can't be deferred behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary because it affects the initial page load. The page can't be prerendered, so navigations block instead of being [instant](https://preview.nextjs.org/docs/app/guides/instant-navigation). During [prerendering](/docs/app/glossary#prerendering), [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport) performed an uncached data access ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database call, [`await connection()`](/docs/app/api-reference/functions/connection)). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, viewport metadata can't be deferred behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary because it affects the initial page load. The page can't be prerendered, so navigations block instead of being [instant](/docs/app/guides/instant-navigation).
Request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)) in `generateViewport()` have different fixes. See [Next.js encountered runtime data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-runtime). The metadata equivalent is handled at [Uncached data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-dynamic). For errors in the page body rather than viewport, see [Next.js encountered uncached data during prerendering](/docs/messages/blocking-prerender-dynamic). Request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)) in `generateViewport()` have different fixes. See [Next.js encountered runtime data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-runtime). The metadata equivalent is handled at [Uncached data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-dynamic). For errors in the page body rather than viewport, see [Next.js encountered uncached data during prerendering](/docs/messages/blocking-prerender-dynamic).
## Ways to fix this ## Ways to fix this
...@@ -53,9 +52,9 @@ Request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-refer ...@@ -53,9 +52,9 @@ Request-bound reads ([`cookies()`](https://preview.nextjs.org/docs/app/api-refer
## Cache the viewport data ## Cache the viewport data
Choose this fix when the viewport values come from an external source (database, CMS) but don't need to change on every request. Add the [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) directive as the first statement inside [`generateViewport()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport). Next.js caches the returned viewport object and includes it in the prerender. Choose this fix when the viewport values come from an external source (database, CMS) but don't need to change on every request. Add the [`use cache`](/docs/app/api-reference/directives/use-cache) directive as the first statement inside [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport). Next.js caches the returned viewport object and includes it in the prerender.
This fix does not apply to [`connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection). The point of `connection()` is to opt into per-request rendering, so caching it would defeat the purpose. Use [Allow blocking route](#allow-blocking-route) instead. This fix does not apply to [`connection()`](/docs/app/api-reference/functions/connection). The point of `connection()` is to opt into per-request rendering, so caching it would defeat the purpose. Use [Allow blocking route](#allow-blocking-route) instead.
### Patterns ### Patterns
...@@ -81,20 +80,20 @@ export default function RootLayout({ children }) { ...@@ -81,20 +80,20 @@ export default function RootLayout({ children }) {
} }
``` ```
Learn more: [Caching with `use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). Learn more: [Caching with `use cache`](/docs/app/api-reference/directives/use-cache).
### Trade-off ### Trade-off
Freshness depends on the cache configuration. The viewport stays the same until [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) expires or [`cacheTag`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheTag) is invalidated. Freshness depends on the cache configuration. The viewport stays the same until [`cacheLife`](/docs/app/api-reference/functions/cacheLife) expires or [`cacheTag`](/docs/app/api-reference/functions/cacheTag) is invalidated.
### Gotchas ### Gotchas
- Inside a [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache) scope, you can't call [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) or [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers). If the viewport needs a request-bound value (a theme color from a cookie), use [Allow blocking route](#allow-blocking-route) instead. - Inside a [`use cache`](/docs/app/api-reference/directives/use-cache) scope, you can't call [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers). If the viewport needs a request-bound value (a theme color from a cookie), use [Allow blocking route](#allow-blocking-route) instead.
- A short [`cacheLife`](https://preview.nextjs.org/docs/app/api-reference/functions/cacheLife) (a profile whose `revalidate` is shorter than the prerender's effective lifetime) prevents the viewport from being included in the prerender. Use a longer profile if you want the viewport included in the static shell. - A short [`cacheLife`](/docs/app/api-reference/functions/cacheLife) (a profile whose `revalidate` is shorter than the prerender's effective lifetime) prevents the viewport from being included in the prerender. Use a longer profile if you want the viewport included in the static shell.
## Allow blocking route ## Allow blocking route
Choose this fix when the viewport data is genuinely uncacheable. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes. Choose this fix when the viewport data is genuinely uncacheable. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes.
Unlike page body content, viewport metadata can't be deferred behind [`<Suspense>`](https://react.dev/reference/react/Suspense) because it affects the initial HTML `<head>`. Making the viewport dynamic means the entire page navigation blocks. Unlike page body content, viewport metadata can't be deferred behind [`<Suspense>`](https://react.dev/reference/react/Suspense) because it affects the initial HTML `<head>`. Making the viewport dynamic means the entire page navigation blocks.
...@@ -102,7 +101,7 @@ Unlike page body content, viewport metadata can't be deferred behind [`<Suspense ...@@ -102,7 +101,7 @@ Unlike page body content, viewport metadata can't be deferred behind [`<Suspense
#### Opt the layout out #### Opt the layout out
Set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout that defines `generateViewport`. This allows that layout segment to block while descendant segments remain independently validated. Apply this to the nested layout that owns the dynamic viewport, not the root layout, so the opt-out is scoped to the affected segment. Set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout that defines `generateViewport`. This allows that layout segment to block while descendant segments remain independently validated. Apply this to the nested layout that owns the dynamic viewport, not the root layout, so the opt-out is scoped to the affected segment.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
import { db } from './db' import { db } from './db'
...@@ -119,7 +118,7 @@ export default function DashboardLayout({ children }) { ...@@ -119,7 +118,7 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use this pattern when: Use this pattern when:
...@@ -134,24 +133,24 @@ Navigations to this route are not instant. The user waits for the full server re ...@@ -134,24 +133,24 @@ Navigations to this route are not instant. The user waits for the full server re
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- This export does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route. - This export does not disable [prerendering](/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route.
- Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateViewport` and must be statically prerendered. [`instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) opts the route out of validation but does not let those routes through, so the build still fails when they prerender. If your root layout's `generateViewport` depends on request data, [Cache the viewport data](#cache-the-viewport-data) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateViewport`. - Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateViewport` and must be statically prerendered. [`instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) opts the route out of validation but does not let those routes through, so the build still fails when they prerender. If your root layout's `generateViewport` depends on request data, [Cache the viewport data](#cache-the-viewport-data) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateViewport`.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,15 +17,14 @@ kind: insight ...@@ -17,15 +17,14 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), [`generateViewport()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport) read a per-request value ([`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, viewport metadata can't be deferred behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary because it affects the initial page load. The page can't be prerendered, so navigations block instead of being [instant](https://preview.nextjs.org/docs/app/guides/instant-navigation). During [prerendering](/docs/app/glossary#prerendering), [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport) read a per-request value ([`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`params`](/docs/app/api-reference/file-conventions/page#params-optional), [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, viewport metadata can't be deferred behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary because it affects the initial page load. The page can't be prerendered, so navigations block instead of being [instant](/docs/app/guides/instant-navigation).
Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](https://preview.nextjs.org/docs/app/api-reference/functions/connection)) in `generateViewport()` have different fixes. See [Next.js encountered uncached data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-dynamic). The metadata equivalent is handled at [Runtime data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-runtime). For errors in the page body rather than viewport, see [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime). Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch), database calls, [`await connection()`](/docs/app/api-reference/functions/connection)) in `generateViewport()` have different fixes. See [Next.js encountered uncached data in `generateViewport()`](/docs/messages/blocking-prerender-viewport-dynamic). The metadata equivalent is handled at [Runtime data in `generateMetadata()`](/docs/messages/blocking-prerender-metadata-runtime). For errors in the page body rather than viewport, see [Next.js encountered runtime data during prerendering](/docs/messages/blocking-prerender-runtime).
## Ways to fix this ## Ways to fix this
...@@ -53,7 +52,7 @@ Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web ...@@ -53,7 +52,7 @@ Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web
## Use static viewport ## Use static viewport
Choose this fix when the viewport doesn't actually need the per-request data, either because the values are known at build time, or because the dependency on runtime data is accidental and can be refactored away. Replace [`generateViewport()`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport) with a static [`viewport`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport#the-viewport-object) export, or rewrite `generateViewport()` so it no longer reads [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies), [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers), or other request-bound APIs. The values are evaluated once during the build. Choose this fix when the viewport doesn't actually need the per-request data, either because the values are known at build time, or because the dependency on runtime data is accidental and can be refactored away. Replace [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport) with a static [`viewport`](/docs/app/api-reference/functions/generate-viewport#the-viewport-object) export, or rewrite `generateViewport()` so it no longer reads [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), or other request-bound APIs. The values are evaluated once during the build.
### Patterns ### Patterns
...@@ -77,7 +76,7 @@ export default function RootLayout({ children }) { ...@@ -77,7 +76,7 @@ export default function RootLayout({ children }) {
} }
``` ```
Learn more: [Static viewport](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport#the-viewport-object). Learn more: [Static viewport](/docs/app/api-reference/functions/generate-viewport#the-viewport-object).
### Trade-off ### Trade-off
...@@ -86,11 +85,11 @@ Static viewport can't reflect per-request values like a user's preferred theme c ...@@ -86,11 +85,11 @@ Static viewport can't reflect per-request values like a user's preferred theme c
### Gotchas ### Gotchas
- The `viewport` export is typically set in the root layout. Changing a layout's viewport affects every route in its subtree. - The `viewport` export is typically set in the root layout. Changing a layout's viewport affects every route in its subtree.
- [`themeColor`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-viewport#themecolor) is the most common reason for a dynamic `generateViewport`. Consider whether a single static value covers all cases before resorting to a blocking route. - [`themeColor`](/docs/app/api-reference/functions/generate-viewport#themecolor) is the most common reason for a dynamic `generateViewport`. Consider whether a single static value covers all cases before resorting to a blocking route.
## Allow blocking route ## Allow blocking route
Choose this fix when the viewport genuinely requires per-request data (a theme color from a cookie, a user-preferred width) and a static export isn't feasible. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes. Choose this fix when the viewport genuinely requires per-request data (a theme color from a cookie, a user-preferred width) and a static export isn't feasible. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation. The page renders on every request and the navigation blocks until that render completes.
Unlike page body content, viewport metadata can't be deferred behind [`<Suspense>`](https://react.dev/reference/react/Suspense) because it affects the initial HTML `<head>`. Making the viewport dynamic means the entire page navigation blocks. Unlike page body content, viewport metadata can't be deferred behind [`<Suspense>`](https://react.dev/reference/react/Suspense) because it affects the initial HTML `<head>`. Making the viewport dynamic means the entire page navigation blocks.
...@@ -98,7 +97,7 @@ Unlike page body content, viewport metadata can't be deferred behind [`<Suspense ...@@ -98,7 +97,7 @@ Unlike page body content, viewport metadata can't be deferred behind [`<Suspense
#### Opt the layout out #### Opt the layout out
Set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout that defines `generateViewport`. This allows that layout segment to block while descendant segments remain independently validated. Apply this to the nested layout that owns the dynamic viewport, not the root layout, so the opt-out is scoped to the affected segment. Set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout that defines `generateViewport`. This allows that layout segment to block while descendant segments remain independently validated. Apply this to the nested layout that owns the dynamic viewport, not the root layout, so the opt-out is scoped to the affected segment.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
...@@ -117,7 +116,7 @@ export default function DashboardLayout({ children }) { ...@@ -117,7 +116,7 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use this pattern when: Use this pattern when:
...@@ -132,25 +131,25 @@ Navigations to this route are not instant. The user waits for the full server re ...@@ -132,25 +131,25 @@ Navigations to this route are not instant. The user waits for the full server re
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- This export does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route. - This export does not disable [prerendering](/docs/app/glossary#prerendering). The route still prerenders if it can. It only disables instant-navigation validation for the route.
- If the dynamic viewport is the only reason the route blocks, consider whether a static default covers most users. A static `themeColor` with a client-side correction after hydration may give a better experience than blocking the entire navigation. - If the dynamic viewport is the only reason the route blocks, consider whether a static default covers most users. A static `themeColor` with a client-side correction after hydration may give a better experience than blocking the entire navigation.
- Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateViewport` and must be statically prerendered. [`instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) opts the route out of validation but does not let those routes through, so the build still fails when they prerender. If your root layout's `generateViewport` depends on request data, [Use static viewport](#use-static-viewport) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateViewport`. - Framework-synthesized routes (`/_not-found`, `/_global-error`) inherit the root layout's `generateViewport` and must be statically prerendered. [`instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) opts the route out of validation but does not let those routes through, so the build still fails when they prerender. If your root layout's `generateViewport` depends on request data, [Use static viewport](#use-static-viewport) instead, or move to [`global-not-found.js`](/docs/app/api-reference/file-conventions/not-found#global-not-foundjs-experimental), which bypasses the root layout entirely and avoids inheriting its `generateViewport`.
## Verifying the fix ## Verifying the fix
After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary placed around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,15 +17,14 @@ kind: insight ...@@ -17,15 +17,14 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During a [client-side navigation](https://preview.nextjs.org/docs/app/glossary#client-side-navigation), a [`<Link prefetch={true}>`](https://preview.nextjs.org/docs/app/api-reference/components/link) navigated to a route that has not enabled [Partial Prefetching](https://preview.nextjs.org/docs/app/glossary#partial-prefetching). With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `prefetch={true}` is a legacy "full" prefetch that pulls down the route's dynamic data along with its [App Shell](https://preview.nextjs.org/docs/app/glossary#app-shell). This will lead to slower, more expensive prefetches. During a [client-side navigation](/docs/app/glossary#client-side-navigation), a [`<Link prefetch={true}>`](/docs/app/api-reference/components/link) navigated to a route that has not enabled [Partial Prefetching](/docs/app/glossary#partial-prefetching). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `prefetch={true}` is a legacy "full" prefetch that pulls down the route's dynamic data along with its [App Shell](/docs/app/glossary#app-shell). This will lead to slower, more expensive prefetches.
Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, leaving you free to choose when it loads: at navigation via [streaming](https://preview.nextjs.org/docs/app/glossary#streaming), ahead of time via [runtime prefetching](https://preview.nextjs.org/docs/app/guides/runtime-prefetching), or not at all. The check fires at navigation time, not prefetch time, so existing apps that have recently enabled Cache Components are not flooded with warnings for every `<Link prefetch={true}>` on the page. Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, leaving you free to choose when it loads: at navigation via [streaming](/docs/app/glossary#streaming), ahead of time via [per-link prefetching](/docs/app/guides/optimizing-prefetching), or not at all. The check fires at navigation time, not prefetch time, so existing apps that have recently enabled Cache Components are not flooded with warnings for every `<Link prefetch={true}>` on the page.
## Ways to fix this ## Ways to fix this
...@@ -62,13 +61,13 @@ Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, ...@@ -62,13 +61,13 @@ Routes that opt into Partial Prefetching skip the dynamic data at prefetch time,
## Opt into Partial Prefetching ## Opt into Partial Prefetching
Choose this fix when the target route has an [App Shell](https://preview.nextjs.org/docs/app/glossary#app-shell) with dynamic content below it. Opting into Partial Prefetching tells Next.js to prefetch only the App Shell and defer the dynamic data to navigation. Opt in per-route or app-wide, and from there layer on further prefetch optimizations. Choose this fix when the target route has an [App Shell](/docs/app/glossary#app-shell) with dynamic content below it. Opting into Partial Prefetching tells Next.js to prefetch only the App Shell and defer the dynamic data to navigation. After opting in per route or app-wide, decide whether selected links should also prefetch URL-specific content.
### Patterns ### Patterns
#### Per-route opt-in #### Per-route opt-in
Export [`prefetch`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/prefetch) from the page or layout of the route the link points at. Export [`prefetch`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) from the page or layout of the route the link points at.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
export const prefetch = 'partial' export const prefetch = 'partial'
...@@ -80,7 +79,7 @@ export default function DashboardPage() { ...@@ -80,7 +79,7 @@ export default function DashboardPage() {
#### App-wide opt-in #### App-wide opt-in
Set [`partialPrefetching`](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/partialPrefetching) to `true` in `next.config` to opt the whole app in. Set [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) to `true` in `next.config` to opt the whole app in.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
...@@ -92,8 +91,8 @@ module.exports = { ...@@ -92,8 +91,8 @@ module.exports = {
`'partial'` prefetches only the App Shell, which is the route's static and cached content. Uncached dynamic data is no longer prefetched. To keep prefetching content that came down with `prefetch={true}`, work through two steps. `'partial'` prefetches only the App Shell, which is the route's static and cached content. Uncached dynamic data is no longer prefetched. To keep prefetching content that came down with `prefetch={true}`, work through two steps.
1. Cache it with [`use cache`](https://preview.nextjs.org/docs/app/api-reference/directives/use-cache). If the content doesn't depend on the URL, it gets included in the App Shell and that's enough. 1. Cache it with [`use cache`](/docs/app/api-reference/directives/use-cache). If the content doesn't depend on the URL, it gets included in the App Shell and that's enough.
2. If it depends on per-link runtime data (`params`, `searchParams`), it can't be included in the shared App Shell. With Partial Prefetching enabled, `prefetch={true}` opts the link into [runtime prefetching](https://preview.nextjs.org/docs/app/guides/runtime-prefetching), so the cached content is prefetched behind the runtime read. 2. If it depends on URL data (`params`, `searchParams`), it can't be included in the shared App Shell. With Partial Prefetching enabled, `prefetch={true}` opts the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching), so the cached content can resolve before navigation.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -120,7 +119,7 @@ export default function DashboardPage({ searchParams }) { ...@@ -120,7 +119,7 @@ export default function DashboardPage({ searchParams }) {
} }
``` ```
Learn more: [Adopting Partial Prefetching](https://preview.nextjs.org/docs/app/guides/adopting-partial-prefetching). Learn more: [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching).
### Trade-off ### Trade-off
...@@ -128,7 +127,7 @@ The route's dynamic data isn't included in the prefetch. The user sees the App S ...@@ -128,7 +127,7 @@ The route's dynamic data isn't included in the prefetch. The user sees the App S
### Gotchas ### Gotchas
- Partial Prefetching only works with [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled. - Partial Prefetching only works with [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled.
- If the route doesn't have a clear App Shell (everything below the layout reads dynamic data), Partial Prefetching has nothing to prefetch and behaves the same as no prefetch. Move static content above the dynamic boundary first. - If the route doesn't have a clear App Shell (everything below the layout reads dynamic data), Partial Prefetching has nothing to prefetch and behaves the same as no prefetch. Move static content above the dynamic boundary first.
## Use the default prefetch ## Use the default prefetch
...@@ -154,11 +153,11 @@ The link no longer forces a full prefetch. The user gets the App Shell (static a ...@@ -154,11 +153,11 @@ The link no longer forces a full prefetch. The user gets the App Shell (static a
### Gotchas ### Gotchas
- Removing `prefetch={true}` does not disable prefetching. It falls back to the default. To disable prefetching entirely, use `prefetch={false}`. - Removing `prefetch={true}` does not disable prefetching. It falls back to the default. To disable prefetching entirely, use `prefetch={false}`.
- See [Adopting Partial Prefetching](https://preview.nextjs.org/docs/app/guides/adopting-partial-prefetching) for the full table of what each `<Link>` prop downloads under each configuration. - See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full table of what each `<Link>` prop downloads under each configuration.
## Disable validation on this route ## Disable validation on this route
Choose this fix when you need the legacy full prefetch behavior and cannot adopt Partial Prefetching for the target route. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the target route opts it out of instant-navigation validation. Choose this fix when you need the legacy full prefetch behavior and cannot adopt Partial Prefetching for the target route. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the target route opts it out of instant-navigation validation.
### Patterns ### Patterns
...@@ -186,16 +185,16 @@ The link continues to do a full prefetch, including dynamic data, and the warnin ...@@ -186,16 +185,16 @@ The link continues to do a full prefetch, including dynamic data, and the warnin
After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
Depending on your [validation level](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), this may only surface in development. Depending on your [validation level](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), this may only surface in development.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,17 +17,16 @@ kind: insight ...@@ -17,17 +17,16 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During a [client-side navigation](https://preview.nextjs.org/docs/app/glossary#client-side-navigation), a Server Component read [`params`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#params-optional) or [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional) outside of a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. With [Partial Prefetching](https://preview.nextjs.org/docs/app/glossary#partial-prefetching) enabled, Next.js extracts one [App Shell](https://preview.nextjs.org/docs/app/glossary#app-shell) from the route ahead of the click, so every link to it reuses the same prefetch instead of fetching a fresh one per URL. During a [client-side navigation](/docs/app/glossary#client-side-navigation), a Server Component read [`params`](/docs/app/api-reference/file-conventions/page#params-optional) or [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) outside of a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled, Next.js extracts one [App Shell](/docs/app/glossary#app-shell) from the route ahead of the click, so every link to it reuses the same prefetch instead of fetching a fresh one per URL.
The `params` and `searchParams` props are [URL data](https://preview.nextjs.org/docs/app/glossary#url-data): they're specific to a single URL, so reading them outside a `<Suspense>` boundary ties the App Shell to one link. Next.js can no longer reuse it across links, and navigations to this route may not be instant. The `params` and `searchParams` props are [URL data](/docs/app/glossary#url-data): they're specific to a single URL, so reading them outside a `<Suspense>` boundary ties the App Shell to one link. Next.js can no longer reuse it across links, and navigations to this route may not be instant.
The check runs when you load the route and when you navigate to it. The App Shell itself is only used for client-side navigations: the initial load has its own validation against the route's [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell), where the same read surfaces as [runtime data during prerendering](/docs/messages/blocking-prerender-runtime). For URL data read through client hooks like [`useSearchParams`](https://preview.nextjs.org/docs/app/api-reference/functions/use-search-params), see [URL data in a Client Component outside of Suspense](/docs/messages/blocking-prerender-client-hook). The check runs when you load the route and when you navigate to it. The App Shell itself is only used for client-side navigations: the initial load has its own validation against the route's [static shell](/docs/app/glossary#static-shell), where the same read surfaces as [runtime data during prerendering](/docs/messages/blocking-prerender-runtime). For URL data read through client hooks like [`useSearchParams`](/docs/app/api-reference/functions/use-search-params), see [URL data in a Client Component outside of Suspense](/docs/messages/blocking-prerender-client-hook).
## Ways to fix this ## Ways to fix this
...@@ -55,7 +54,7 @@ The check runs when you load the route and when you navigate to it. The App Shel ...@@ -55,7 +54,7 @@ The check runs when you load the route and when you navigate to it. The App Shel
## Wrap in or move into Suspense ## Wrap in or move into Suspense
Choose this fix when the URL-specific content can render after the navigation. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary keeps the read out of the App Shell, so every link still shares the same prefetch and only the wrapped region [streams](https://preview.nextjs.org/docs/app/glossary#streaming) in after the navigation. Choose this fix when the URL-specific content can render after the navigation. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary keeps the read out of the App Shell, so every link still shares the same prefetch and only the wrapped region [streams](/docs/app/glossary#streaming) in after the navigation.
### Patterns ### Patterns
...@@ -87,7 +86,7 @@ export async function Results({ searchParams }) { ...@@ -87,7 +86,7 @@ export async function Results({ searchParams }) {
} }
``` ```
Learn more: [`searchParams`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional). Learn more: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional).
#### Read `params` in the leaf that needs it #### Read `params` in the leaf that needs it
...@@ -116,21 +115,21 @@ export async function ProductDetails({ params }) { ...@@ -116,21 +115,21 @@ export async function ProductDetails({ params }) {
} }
``` ```
Learn more: [Streaming](https://preview.nextjs.org/docs/app/guides/streaming). Learn more: [Streaming](/docs/app/guides/streaming).
### Trade-off ### Trade-off
The shared parts of the route are prefetched, and the URL-dependent region streams in after navigation, so the user sees a fallback for that region. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](https://preview.nextjs.org/docs/app/guides/streaming#cls-cumulative-layout-shift). The shared parts of the route are prefetched, and the URL-dependent region streams in after navigation, so the user sees a fallback for that region. Design the fallback so it approximates the final layout. A generic spinner causes a layout shift when content arrives. See [minimizing layout shift](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas ### Gotchas
- [`cookies()`](https://preview.nextjs.org/docs/app/api-reference/functions/cookies) and [`headers()`](https://preview.nextjs.org/docs/app/api-reference/functions/headers) don't trigger this error, even outside `<Suspense>`. They vary per session, not per link, so the App Shell stays reusable across links. The initial load's [static shell](https://preview.nextjs.org/docs/app/glossary#static-shell) may still need them behind `<Suspense>`, and that requirement surfaces separately as [runtime data during prerendering](/docs/messages/blocking-prerender-runtime). - [`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers) don't trigger this error, even outside `<Suspense>`. They vary per session, not per link, so the App Shell stays reusable across links. The initial load's [static shell](/docs/app/glossary#static-shell) may still need them behind `<Suspense>`, and that requirement surfaces separately as [runtime data during prerendering](/docs/messages/blocking-prerender-runtime).
- Making the route static with [`generateStaticParams`](https://preview.nextjs.org/docs/app/api-reference/functions/generate-static-params) does not resolve this error. A static param is still specific to one URL, so it can't be part of a prefetch shared across links. - Making the route static with [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) does not resolve this error. A static param is still specific to one URL, so it can't be part of a prefetch shared across links.
- The `params` and `searchParams` props are promises. Passing the promise down without awaiting it keeps the rest of the route in the shared prefetch. Awaiting it above the boundary pulls the URL data back in. - The `params` and `searchParams` props are promises. Passing the promise down without awaiting it keeps the rest of the route in the shared prefetch. Awaiting it above the boundary pulls the URL data back in.
## Allow blocking route ## Allow blocking route
Choose this fix when the route genuinely can't provide a shared App Shell — it needs the URL data high in the tree to decide what to render — and you accept that navigations to it won't be instant. Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` marks the segment as allowed to block: it renders per navigation instead of reusing a shared prefetch. Choose this fix when the route genuinely can't provide a shared App Shell — it needs the URL data high in the tree to decide what to render — and you accept that navigations to it won't be instant. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` marks the segment as allowed to block: it renders per navigation instead of reusing a shared prefetch.
### Patterns ### Patterns
...@@ -147,11 +146,11 @@ export default async function Page({ searchParams }) { ...@@ -147,11 +146,11 @@ export default async function Page({ searchParams }) {
} }
``` ```
Learn more: [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation). Learn more: [Ensuring instant navigations](/docs/app/guides/instant-navigation).
#### Opt the layout out #### Opt the layout out
When a shared layout reads the URL data, set [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated. When a shared layout reads the URL data, set [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the layout. This allows that layout segment to block while descendant segments remain independently validated.
```jsx filename="app/dashboard/layout.js" ```jsx filename="app/dashboard/layout.js"
export const instant = false export const instant = false
...@@ -161,7 +160,7 @@ export default function DashboardLayout({ children }) { ...@@ -161,7 +160,7 @@ export default function DashboardLayout({ children }) {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use either pattern when: Use either pattern when:
...@@ -176,24 +175,24 @@ Navigations to this route are not instant. Without an App Shell, it renders per ...@@ -176,24 +175,24 @@ Navigations to this route are not instant. Without an App Shell, it renders per
### Gotchas ### Gotchas
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts only the segment that exports it out. Descendant segments are still validated by the global default.
- Allowing the route to block does not disable [Partial Prefetching](https://preview.nextjs.org/docs/app/glossary#partial-prefetching) or prefetching. It only exempts the segment from instant-navigation validation. - Allowing the route to block does not disable [Partial Prefetching](/docs/app/glossary#partial-prefetching) or prefetching. It only exempts the segment from instant-navigation validation.
- `instant = false` allows the route to block for all instant-navigation checks, not only this one. That includes [runtime data during prerendering](/docs/messages/blocking-prerender-runtime) errors and [unrendered segment](/docs/messages/instant-unrendered-segment) warnings for the route. - `instant = false` allows the route to block for all instant-navigation checks, not only this one. That includes [runtime data during prerendering](/docs/messages/blocking-prerender-runtime) errors and [unrendered segment](/docs/messages/instant-unrendered-segment) warnings for the route.
## Verifying the fix ## Verifying the fix
After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. Depending on your [validation level](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), the insight may only surface in development. After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. Depending on your [validation level](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), the insight may only surface in development.
In [`next dev`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](https://preview.nextjs.org/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component with file paths and line numbers. When working from a build instead, the default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -17,13 +17,12 @@ kind: insight ...@@ -17,13 +17,12 @@ kind: insight
This Insight is part of the [Instant This Insight is part of the [Instant
Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature Navigations](https://nextjs.org/blog/next-16-3-instant-navigations) feature
introduced in Next.js 16.3. If you're new to it, start with the [Ensuring introduced in Next.js 16.3. If you're new to it, start with the [Ensuring
instant instant navigations](/docs/app/guides/instant-navigation) guide for an
navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) overview of what instant navigations are and how Next.js validates them, then
guide for an overview of what instant navigations are and how Next.js come back here for the specific fix.
validates them, then come back here for the specific fix.
</div> </div>
During [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering), a segment in the route tree was dropped from rendering. With [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js validates that every segment can produce an [instant navigation](https://preview.nextjs.org/docs/app/guides/instant-navigation). When a segment is not rendered, that validation can't run and issues that would prevent instant navigation go undetected. During [prerendering](/docs/app/glossary#prerendering), a segment in the route tree was dropped from rendering. With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, Next.js validates that every segment can produce an [instant navigation](/docs/app/guides/instant-navigation). When a segment is not rendered, that validation can't run and issues that would prevent instant navigation go undetected.
This typically happens when a layout conditionally omits `{children}` or a parallel route slot is not rendered. This typically happens when a layout conditionally omits `{children}` or a parallel route slot is not rendered.
...@@ -130,7 +129,7 @@ export default async function DashboardPage() { ...@@ -130,7 +129,7 @@ export default async function DashboardPage() {
} }
``` ```
Learn more: [Authentication](https://preview.nextjs.org/docs/app/guides/authentication). Learn more: [Authentication](/docs/app/guides/authentication).
### Trade-off ### Trade-off
...@@ -143,7 +142,7 @@ The segment is always in the render tree, which means Next.js validates it on ev ...@@ -143,7 +142,7 @@ The segment is always in the render tree, which means Next.js validates it on ev
## Skip validation on the segment ## Skip validation on the segment
Choose this fix when the segment is intentionally not rendered in certain states (a modal that only appears on interaction, a slot gated by authentication). Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the dropped segment tells Next.js to skip validation for it. Choose this fix when the segment is intentionally not rendered in certain states (a modal that only appears on interaction, a slot gated by authentication). Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the dropped segment tells Next.js to skip validation for it.
### Patterns ### Patterns
...@@ -159,7 +158,7 @@ export default function ModalPage() { ...@@ -159,7 +158,7 @@ export default function ModalPage() {
} }
``` ```
Learn more: [Route segment `instant` config](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant). Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
### Trade-off ### Trade-off
...@@ -168,22 +167,22 @@ The segment is exempt from instant-navigation validation. If it has issues that ...@@ -168,22 +167,22 @@ The segment is exempt from instant-navigation validation. If it has issues that
### Gotchas ### Gotchas
- The export must be on the **dropped segment's own file** (page or layout), not on a parent. The framework walks top-down and the first explicit config wins. - The export must be on the **dropped segment's own file** (page or layout), not on a parent. The framework walks top-down and the first explicit config wins.
- Setting [`instant`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` does not disable [prerendering](https://preview.nextjs.org/docs/app/glossary#prerendering). The segment still prerenders if it can. It only disables the validation error. - Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` does not disable [prerendering](/docs/app/glossary#prerendering). The segment still prerenders if it can. It only disables the validation error.
## Verifying the fix ## Verifying the fix
After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation. After applying a fix, navigate to the route and confirm the insight no longer appears in the dev overlay and the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in. A [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary around the whole page body can pass validation with an empty shell, which defeats the point of an instant navigation.
Depending on your [validation level](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), this may only surface in development. Depending on your [validation level](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults), this may only surface in development.
## Don't want this validation? ## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](https://preview.nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error. Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations. - **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](https://preview.nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`. - **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](https://preview.nextjs.org/docs/app/guides/instant-navigation) for the full model. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Related Insights ## Related Insights
......
...@@ -4,7 +4,7 @@ title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or anothe ...@@ -4,7 +4,7 @@ title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or anothe
## Why This Error Occurred ## Why This Error Occurred
An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` package was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random crypto values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Accessing random values synchronously without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` package was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random crypto values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Accessing random values synchronously without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -4,7 +4,7 @@ title: Cannot access `Date.now()`, `Date()`, or `new Date()` before other uncach ...@@ -4,7 +4,7 @@ title: Cannot access `Date.now()`, `Date()`, or `new Date()` before other uncach
## Why This Error Occurred ## Why This Error Occurred
`Date.now()`, `Date()`, or `new Date()` was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically reading the current time can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Reading the current time without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. `Date.now()`, `Date()`, or `new Date()` was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically reading the current time can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Reading the current time without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -4,7 +4,7 @@ title: Cannot access `Math.random()` before other uncached data or `connection() ...@@ -4,7 +4,7 @@ title: Cannot access `Math.random()` before other uncached data or `connection()
## Why This Error Occurred ## Why This Error Occurred
`Math.random()` was called in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Accessing random values without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. `Math.random()` was called in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Accessing random values without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
title: No Before Interactive Script Outside Document title: No Before Interactive Script Outside Document
--- ---
> Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `app/layout.jsx` or `pages/_document.js`. > Prevent usage of `next/script`'s `beforeInteractive` strategy outside of a root layout or `pages/_document.js`.
## Why This Error Occurred ## Why This Error Occurred
You cannot use the `next/script` component with the `beforeInteractive` strategy outside `app/layout.jsx` or `pages/_document.js`. That's because `beforeInteractive` strategy only works inside **`app/layout.jsx`** or **`pages/_document.js`** and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side). You cannot use the `next/script` component with the `beforeInteractive` strategy outside a root layout or `pages/_document.js`. That's because `beforeInteractive` strategy only works inside a **root layout** or **`pages/_document.js`** and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
## Possible Ways to Fix It ## Possible Ways to Fix It
### App Router ### App Router
If you want a global script, and you are using the App Router, move the script inside `app/layout.jsx`. If you want a global script, and you are using the App Router, move the script inside a [root layout](/docs/app/api-reference/file-conventions/layout#root-layout), any layout without a `layout.js` above it.
```jsx filename="app/layout.jsx" ```jsx filename="app/layout.jsx"
import Script from 'next/script' import Script from 'next/script'
......
---
title: '`prefetch={true}` is deprecated (Pages Router)'
---
## Why This Error Occurred
This message is about the Pages Router [`<Link>`](/docs/pages/api-reference/components/link) component from `next/link`.
Since [Next.js 9](/blog/next-9#prefetching-in-viewport-links), the Pages Router `<Link>` prefetches automatically: as a link enters the viewport, Next.js prefetches the route's assets in the background. Passing `prefetch={true}` asks for behavior that is already the default, so the prop is redundant and deprecated.
Prefetch requests are low priority and yield to `fetch()` and XHR requests. Next.js also skips them when the visitor has data-saver enabled.
## Possible Ways to Fix It
Remove the redundant `prefetch` prop, since automatic prefetching is already the default:
```jsx
// Before
<Link href="/about" prefetch={true}>
About
</Link>
// After
<Link href="/about">About</Link>
```
To turn prefetching off for a specific link, set `prefetch={false}`:
```jsx
<Link href="/about" prefetch={false}>
About
</Link>
```
---
title: '`prefetch={true}` is deprecated'
---
## Why This Error Occurred
In [Nextjs 9](/blog/next-9#prefetching-in-viewport-links), the behavior of the `<Link prefetch>` attribute was changed from opt in to opt out. This means that the `<Link prefetch={true}>` is **no longer required**.
`<Link>` will automatically prefetch pages in the background as they appear in the view. If certain pages are rarely visited you can manually set prefetch to false, here's how:
This feature improves the responsiveness of your application by making navigations to new pages quicker.
Next.js uses an Intersection Observer to prefetch the assets necessary in the background.
These requests have low-priority and yield to `fetch()` or XHR requests. Next.js will avoid automatically prefetching if the user has data-saver enabled.
## Possible Ways to Fix It
`<Link prefetch={true}>` is now the default behavior and setting it is no longer required. You can safely remove the `prefetch` attribute.
You can opt out of prefetching using `<Link prefetch={false}>`.
# A secret used to encrypt the session cookie. Must be at least 32 characters.
# Generate one with: openssl rand -base64 32
SESSION_PASSWORD=
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Authentication with Cache Components (iron-session)
This example shows how to combine per-user authentication with [Cache Components](https://nextjs.org/docs/app/getting-started/caching). It uses [iron-session](https://github.com/vvo/iron-session) for encrypted cookie sessions, but the caching patterns apply to any session or auth library.
The home page renders a shared, prerendered shell, then renders content that reads the session behind a `Suspense` boundary:
- **Shared data** (`getAnnouncements`) uses [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache) and is part of the static shell.
- **The current user** (`getCurrentUser`) uses [`use cache: private`](https://nextjs.org/docs/app/api-reference/directives/use-cache-private) so it can read the session cookie while staying out of the shared, server-stored cache. It redirects when there is no signed-in user, so reads that start from it are protected.
- **Per-user data** (`lib/data.ts`) exports getters that take no user id. They call `getCurrentUser` and pass the resolved id to an unexported plain `use cache` function with a [`cacheTag`](https://nextjs.org/docs/app/api-reference/functions/cacheTag), so it caches on the server and is invalidated with [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag).
The user data lives in memory (`lib/data.ts`) so the example runs without a database. Replace those functions with your own database queries, and verify passwords with a hashing library such as bcrypt.
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-iron-session-cache-components&project-name=with-iron-session-cache-components&repository-name=with-iron-session-cache-components&env=SESSION_PASSWORD)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash
npx create-next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
```
```bash
yarn create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
```
```bash
pnpm create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
```
```bash
bunx create-next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
```
Copy `.env.example` to `.env.local` and set `SESSION_PASSWORD` to a value of at least 32 characters:
```bash
cp .env.example .env.local
openssl rand -base64 32 # paste the output as SESSION_PASSWORD
```
Then run the development server and sign in with the demo account (`ada@example.com` / `password`):
```bash
npm run dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
"use server";
import { redirect } from "next/navigation";
import { getSession, destroySession } from "@/lib/session";
import { addUserNote } from "@/lib/data";
export async function logout() {
await destroySession();
redirect("/login");
}
export async function addNote(formData: FormData) {
// Re-check the session inside the action. Never trust the client to tell you
// who the current user is.
const session = await getSession();
if (!session.userId) {
redirect("/login");
}
const note = String(formData.get("note") ?? "").trim();
if (note) {
await addUserNote(session.userId, note);
}
}
import type { ReactNode } from "react";
export const metadata = {
title: "iron-session + Cache Components",
description: "Authentication with Next.js Cache Components and iron-session.",
};
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
"use server";
import { redirect } from "next/navigation";
import { saveSession } from "@/lib/session";
import { verifyCredentials } from "@/lib/data";
export type LoginState = { error: string } | null;
export async function login(
_prevState: LoginState,
formData: FormData,
): Promise<LoginState> {
const email = String(formData.get("email") ?? "");
const password = String(formData.get("password") ?? "");
const userId = await verifyCredentials(email, password);
if (!userId) {
return { error: "These credentials do not match our records." };
}
await saveSession({ userId });
redirect("/");
}
"use client";
import { useActionState } from "react";
import { login, type LoginState } from "./actions";
export default function LoginPage() {
const [state, action, pending] = useActionState<LoginState, FormData>(
login,
null,
);
return (
<main>
<h1>Log in</h1>
<form action={action}>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
defaultValue="ada@example.com"
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
defaultValue="password"
/>
</div>
{state?.error && <p>{state.error}</p>}
<button type="submit" disabled={pending}>
Log in
</button>
</form>
</main>
);
}
import { Suspense } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getNote } from "@/lib/data";
async function Note({
params,
}: {
params: PageProps<"/notes/[id]">["params"];
}) {
const { id } = await params;
// `getNote()` resolves the user from the session, so a guessed id cannot
// reach another user's note.
const note = await getNote(id);
if (!note) {
notFound();
}
return <article>{note.text}</article>;
}
export default function NotePage({ params }: PageProps<"/notes/[id]">) {
return (
<main>
<Link href="/">← Back</Link>
<Suspense fallback={<p>Loading note…</p>}>
<Note params={params} />
</Suspense>
</main>
);
}
import { Suspense } from "react";
import Link from "next/link";
import { getCurrentUser } from "@/lib/auth";
import { getAnnouncements, getNotes } from "@/lib/data";
import { addNote, logout } from "./actions";
import { UserProvider } from "./user-provider";
import { UserBadge } from "./user-badge";
async function Announcements() {
const announcements = await getAnnouncements();
return (
<section>
<h2>Announcements</h2>
<ul>
{announcements.map((announcement) => (
<li key={announcement}>{announcement}</li>
))}
</ul>
</section>
);
}
async function Notes() {
// `getNotes()` resolves the user from the session, so there is no id to pass.
const notes = await getNotes();
return (
<section>
<h2>Your notes</h2>
<ul>
{notes.map((note) => (
<li key={note.id}>
<Link href={`/notes/${note.id}`} prefetch={true}>
{note.text}
</Link>
</li>
))}
</ul>
</section>
);
}
function Dashboard() {
// Create the promise once and hand it to the provider without awaiting it, so
// the dashboard chrome renders immediately and each consumer resolves the
// session behind its own boundary.
const userPromise = getCurrentUser();
return (
<UserProvider userPromise={userPromise}>
<section>
<Suspense fallback={<span>Loading…</span>}>
<UserBadge />
</Suspense>
<form action={logout}>
<button type="submit">Log out</button>
</form>
</section>
<Suspense fallback={<p>Loading your notes…</p>}>
<Notes />
</Suspense>
<form action={addNote}>
<input name="note" placeholder="Add a note" />
<button type="submit">Add</button>
</form>
</UserProvider>
);
}
export default function Page() {
return (
<main>
{/* Shared content. Prerendered into the static shell. */}
<Announcements />
{/* Reads the session, so it renders into the per-session App Shell
instead of the shared static shell. */}
<Suspense fallback={<p>Loading your dashboard…</p>}>
<Dashboard />
</Suspense>
</main>
);
}
"use client";
import { useUser } from "./user-provider";
export function UserBadge() {
const user = useUser();
return <span>Signed in as {user.name}</span>;
}
"use client";
import { createContext, use } from "react";
import type { ReactNode } from "react";
import type { User } from "@/lib/auth";
const UserContext = createContext<Promise<User> | null>(null);
export function UserProvider({
userPromise,
children,
}: {
userPromise: Promise<User>;
children: ReactNode;
}) {
return <UserContext value={userPromise}>{children}</UserContext>;
}
export function useUser() {
const userPromise = use(UserContext);
if (!userPromise) {
throw new Error("useUser must be used within a UserProvider");
}
return use(userPromise);
}
import "server-only";
import { redirect } from "next/navigation";
import { cacheLife } from "next/cache";
import { getSession } from "./session";
import { findUserById } from "./data";
export type User = {
id: string;
name: string;
};
// Reads the session cookie, so it must run on every request and cannot live in
// a plain `use cache` scope. `use cache: private` lets it read the cookie while
// keeping the result out of the shared, server-stored cache. Cached scopes are
// prefetchable by default; a `stale` of at least 30 seconds keeps it that way.
export async function getCurrentUser(): Promise<User> {
"use cache: private";
cacheLife({ stale: 60 });
const { userId } = await getSession();
if (!userId) {
redirect("/login");
}
const user = await findUserById(userId);
if (!user) {
redirect("/login");
}
return { id: user.id, name: user.name };
}
import "server-only";
import { cacheLife, cacheTag, updateTag } from "next/cache";
import { getCurrentUser } from "./auth";
// This file stands in for your database. The data lives in memory and resets
// when the server restarts. In a real app, replace these functions with calls
// to your database and verify passwords with a hashing library such as bcrypt.
type UserRecord = {
id: string;
name: string;
email: string;
// Demo only. Never store plaintext passwords in a real application.
password: string;
};
export type Note = {
id: string;
text: string;
};
const users: UserRecord[] = [
{
id: "1",
name: "Ada Lovelace",
email: "ada@example.com",
password: "password",
},
];
const notesByUserId = new Map<string, Note[]>([
["1", [{ id: "n1", text: "Finish the analytical engine notes." }]],
]);
export async function verifyCredentials(
email: string,
password: string,
): Promise<string | null> {
const user = users.find((u) => u.email === email);
if (!user || user.password !== password) {
return null;
}
return user.id;
}
export async function findUserById(id: string) {
return users.find((u) => u.id === id) ?? null;
}
// Shared data. It does not depend on the request, so a plain `use cache`
// scope stores it on the server and includes it in the static shell.
export async function getAnnouncements() {
"use cache";
cacheTag("announcements");
cacheLife("hours");
return [
"Cache Components is now enabled.",
"Session data streams in after the shell.",
];
}
// Takes the id as an argument instead of reading the request, so this stays a
// plain `use cache` scope. The result is stored on the server, keyed by
// `userId`, and tagged for targeted invalidation.
async function getNotesByUserId(userId: string): Promise<Note[]> {
"use cache";
cacheTag(`notes:${userId}`);
cacheLife("minutes");
return notesByUserId.get(userId) ?? [];
}
async function getNoteById(
userId: string,
noteId: string,
): Promise<Note | null> {
"use cache";
cacheTag(`notes:${userId}`);
cacheLife("minutes");
const notes = notesByUserId.get(userId) ?? [];
return notes.find((note) => note.id === noteId) ?? null;
}
// The exported readers resolve the user from the session, so there is no id for
// a caller to get wrong.
export async function getNotes(): Promise<Note[]> {
const user = await getCurrentUser();
return getNotesByUserId(user.id);
}
export async function getNote(noteId: string): Promise<Note | null> {
const user = await getCurrentUser();
return getNoteById(user.id, noteId);
}
// Writes go through a Server Action that has already checked the session, so
// this takes the verified id. See Step 5 of the guide.
export async function addUserNote(userId: string, text: string) {
const existing = notesByUserId.get(userId) ?? [];
const note: Note = { id: crypto.randomUUID(), text };
notesByUserId.set(userId, [...existing, note]);
// Invalidate this user's cached notes so the next read returns fresh data.
updateTag(`notes:${userId}`);
}
import "server-only";
import { cookies } from "next/headers";
import { sealData, unsealData } from "iron-session";
export type SessionData = {
userId?: string;
};
const COOKIE_NAME = "app_session";
const password = process.env.SESSION_PASSWORD!;
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
};
export async function getSession(): Promise<SessionData> {
const cookie = (await cookies()).get(COOKIE_NAME)?.value;
if (!cookie) {
return {};
}
try {
return await unsealData<SessionData>(cookie, { password });
} catch {
// An expired, tampered, or otherwise unsealable cookie (for example after
// SESSION_PASSWORD is rotated) is treated the same as no session, so
// callers redirect to /login instead of hitting the error boundary.
return {};
}
}
export async function saveSession(data: SessionData) {
const sealed = await sealData(data, { password });
(await cookies()).set(COOKIE_NAME, sealed, cookieOptions);
}
export async function destroySession() {
(await cookies()).delete(COOKIE_NAME);
}
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
};
export default nextConfig;
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"iron-session": "^8.0.4",
"next": "latest",
"react": "latest",
"react-dom": "latest"
},
"devDependencies": {
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"typescript": "6.0.3"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
...@@ -17,6 +17,8 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq ...@@ -17,6 +17,8 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq
- **App Router project.** Cache Components is an App Router feature; `cacheComponents: true` does nothing for `pages/` routes. If the project has a `pages/` or `src/pages/` tree but no `app/` or `src/app/` tree, stop and tell the user — Pages → App migration is its own project, not part of this skill. A hybrid app (both `pages/` and `app/`) is fine: the flag affects the `app/` routes; `pages/` routes are unaffected and don't need opt-outs. - **App Router project.** Cache Components is an App Router feature; `cacheComponents: true` does nothing for `pages/` routes. If the project has a `pages/` or `src/pages/` tree but no `app/` or `src/app/` tree, stop and tell the user — Pages → App migration is its own project, not part of this skill. A hybrid app (both `pages/` and `app/`) is fine: the flag affects the `app/` routes; `pages/` routes are unaffected and don't need opt-outs.
- **A resolved app directory.** Locate `next.config.{js,ts,mjs,cjs}` first: that's the project root, and an agent invoked from a subdirectory would otherwise test for `app/` against the wrong `cwd` and find nothing. Look for `app/` and `src/app/` under it, and treat every command and glob in this skill as relative to whichever one exists. If both exist, Next.js builds `app/` and never looks at `src/app/`, so its routes are shadowed and unbuilt — tell the user that and ask which tree to migrate instead of picking one.
- **A runnable app.** The whole loop verifies against `next dev` and a browser, so the app has to boot. If it reads a database or required env at import (e.g. an `env.ts` that throws on a missing `DATABASE_URL`), confirm it actually starts — with the real environment, or local data you stand up — before step 1. Adoption can't be verified against an app that won't run. - **A runnable app.** The whole loop verifies against `next dev` and a browser, so the app has to boot. If it reads a database or required env at import (e.g. an `env.ts` that throws on a missing `DATABASE_URL`), confirm it actually starts — with the real environment, or local data you stand up — before step 1. Adoption can't be verified against an app that won't run.
- **Next.js 16.3 or later.** That release is where the pieces this skill relies on land: top-level `cacheComponents`, `export const instant`, the dev-overlay instant-navigation validation warnings, and the `cache-components-instant-false` codemod. If `next --version` reports below 16.3, upgrade first: - **Next.js 16.3 or later.** That release is where the pieces this skill relies on land: top-level `cacheComponents`, `export const instant`, the dev-overlay instant-navigation validation warnings, and the `cache-components-instant-false` codemod. If `next --version` reports below 16.3, upgrade first:
...@@ -53,7 +55,7 @@ In both, the per-route success bar is the same: **dev loop reports no errors AND ...@@ -53,7 +55,7 @@ In both, the per-route success bar is the same: **dev loop reports no errors AND
Three classes of blocker come up, usually in this order: Three classes of blocker come up, usually in this order:
1. **Request-time reads** (`cookies()`, `headers()`, `await params`, `await searchParams`). All four block when awaited at the top of a page or layout. `params` and `searchParams` often get missed because they're not framed as "request data" the way cookies and headers are. The fix is to push the read into a `<Suspense>`-wrapped child — and for `params`/`searchParams`, forward the promise into the child and await it there; don't `await` at the page top. 1. **Request-time reads** (`cookies()`, `headers()`, `await params`, `await searchParams`). All four block when awaited at the top of a page or layout. `params` and `searchParams` often get missed because they're not framed as "request data" the way cookies and headers are. The fix is to push the read into a `<Suspense>`-wrapped child — and for `params`/`searchParams`, forward the promise into the child and await it there; don't `await` at the page top.
2. **Sync-IO at module/render time** (`new Date()`, `Date.now()`, `Math.random()`, `crypto.randomUUID()`). These fail the build even with `instant = false` — the opt-out doesn't suppress them. If they're in a shared layout, they block every route under it. The codemod can't fix them; you have to translate each one by hand before the build can pass (see the [incremental pre-step](#incremental)). Grep the whole repo for these calls before running anything else. 2. **Sync-IO at module/render time** (`new Date()`, `Date.now()`, `Math.random()`, `crypto.randomUUID()`). These fail the build even with `instant = false` — the opt-out doesn't suppress them. If they're in a shared layout, they block every route under it. The codemod can't fix them; after running it, use the build errors to identify which calls to translate by hand (see the [incremental pre-step](#incremental)).
3. **`"use cache"` files that read request data.** A file with a top-level `"use cache"` directive can't export `instant`; combining the two errors with `Only async functions are allowed to be exported in a "use cache" file.`, which means the directive was wrong for that route. Remove it before running the codemod. 3. **`"use cache"` files that read request data.** A file with a top-level `"use cache"` directive can't export `instant`; combining the two errors with `Only async functions are allowed to be exported in a "use cache" file.`, which means the directive was wrong for that route. Remove it before running the codemod.
## working surfaces ## working surfaces
...@@ -75,7 +77,7 @@ In preference order: ...@@ -75,7 +77,7 @@ In preference order:
1. **[`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) — strongly preferred.** Cross-checks `/_next/mcp` against the live browser via `agent-browser` and surfaces both compile and runtime issues in one pass. The diagnostics (React tree, suspense boundaries, console + network) are richer than poking at `next dev` by hand. 1. **[`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) — strongly preferred.** Cross-checks `/_next/mcp` against the live browser via `agent-browser` and surfaces both compile and runtime issues in one pass. The diagnostics (React tree, suspense boundaries, console + network) are richer than poking at `next dev` by hand.
Install it before starting the loop. Don't wait until you hit something `next dev` alone can't explain. Run: Install it before starting the loop. Don't wait until you hit something `next dev` alone can't explain. It ships alongside this skill, so check whether it is already available first, and install it only if it is not:
```bash ```bash
npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop
...@@ -104,17 +106,9 @@ If there's no user to ask, default to **Incremental** and document the choice. ...@@ -104,17 +106,9 @@ If there's no user to ask, default to **Incremental** and document the choice.
### incremental ### incremental
Before invoking the codemod, fix the two classes of blocker it can't. Before invoking the codemod, fix the blocker that does not require build feedback.
1. **Sync-IO at module/render time.** Grep the whole repo for `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` (not only `app/**/layout.{js,jsx,ts,tsx}` — the read might live in any component imported by a layout). Unblock each match with the `await connection()` + `<Suspense>` fix from its `blocking-prerender-*` error card: it defers the value to request time, exactly as it behaved before the migration, so it needs no product decision. Add this exact comment on the line above the `await connection()`:
```tsx 1. **Incompatible segment configs.** Grep for `^export const (revalidate|dynamic|fetchCache)` across the app directory and translate per the `requires` note above. The codemod does not touch them; leaving them in place fails the build after the codemod.
// TODO: Cache Components adoption. Added to unblock the build: remove this connection() to re-trigger the error and review the fix options.
```
It shares the `TODO: Cache Components adoption` prefix with the comments the codemod writes, so the check-in grep finds both. Removing the `await connection()` makes the error fire again with its fix cards — the same motion as removing an opt-out in the loop.
2. **Incompatible segment configs.** Grep for `^export const (revalidate|dynamic|fetchCache)` across `app/` and translate per the `requires` note above. The codemod does not touch them; leaving them in place fails the build after the codemod.
The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first. The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first.
...@@ -122,9 +116,11 @@ The codemod refuses to run on a dirty working tree. Commit or stash unrelated wo ...@@ -122,9 +116,11 @@ The codemod refuses to run on a dirty working tree. Commit or stash unrelated wo
npx @next/codemod@latest cache-components-instant-false ./app npx @next/codemod@latest cache-components-instant-false ./app
``` ```
Inserts `export const instant = false` (with a `// TODO: Cache Components adoption` comment) into every `app/**/{page,layout,default}` file, skipping files that already declare `instant` and any module marked `"use client"` or `"use server"`. Then set `cacheComponents: true`. The TODO comments are the work queue for the loop. Pass the app directory you resolved in [requires](#requires). A wrong path is not an error: it reports `0 ok` and exits `0`, so read the file count and treat zero as a failed run, not an adopted app.
Inserts `export const instant = false` (with a `// TODO: Cache Components adoption` comment) into every `{page,layout,default}` file under that directory, skipping files that already declare `instant` and any module marked `"use client"` or `"use server"`. Then set `cacheComponents: true`. The TODO comments are the work queue for the loop.
If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand: for every `app/**/{page,layout,default}.{js,jsx,ts,tsx}` that isn't `"use client"` or `"use server"` and doesn't already declare `instant`, insert this after the imports: If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand: for every `{page,layout,default}.{js,jsx,ts,tsx}` in the app directory that isn't `"use client"` or `"use server"` and doesn't already declare `instant`, insert this after the imports:
```ts ```ts
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
...@@ -136,9 +132,19 @@ The codemod opts every segment out, not only the root, on purpose. Resolution is ...@@ -136,9 +132,19 @@ The codemod opts every segment out, not only the root, on purpose. Resolution is
Because the highest opt-out wins, remove them top-down (root layout first, then descend). Removing a leaf's opt-out does nothing while an ancestor still holds one. Because the highest opt-out wins, remove them top-down (root layout first, then descend). Removing a leaf's opt-out does nothing while an ancestor still holds one.
Confirm the pre-step with `next build`. The build is the proof, not the codemod run — a shared layout that calls `new Date()` / `Math.random()` directly still fails regardless of the opt-out (see [background](#background)). Next, run `next build` to surface blockers the codemod could not handle. The build is the proof, not the codemod run — a shared layout that calls `new Date()` / `Math.random()` directly still fails regardless of the opt-out (see [background](#background)). If the normal build reports a sync-IO error without locating the call, rerun that route with `next build --debug-prerender --debug-build-paths="app/path/to/page.tsx"`. For each sync-IO error it reports:
1. **Sync-IO at module/render time.** Use the route, originating file and line, and `/docs/messages/` link in the build output to locate the error. If needed, grep the whole repo for `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` (not only `app/**/layout.{js,jsx,ts,tsx}` — the read might live in any component imported by a layout). Do not change unreported matches. Unblock the reported call with the `await connection()` + `<Suspense>` fix from its `blocking-prerender-*` error card: it defers the value to request time, exactly as it behaved before the migration, so it needs no product decision. Add this exact comment on the line above the `await connection()`:
```tsx
// TODO: Cache Components adoption. Added to unblock the build: remove this connection() to re-trigger the error and review the fix options.
```
It shares the `TODO: Cache Components adoption` prefix with the comments the codemod writes, so the check-in grep finds both. Removing the `await connection()` makes the error fire again with its fix cards — the same motion as removing an opt-out in the loop.
After each fix, rerun the scoped build when available, then run `next build` again to find the next blocker. Repeat until the normal build passes.
After the build passes, confirm the root layout got an opt-out (`grep -n "export const instant" app/layout.*`). The root layout renders every route, including framework routes like `/_not-found`, so if it was missed, add `export const instant = false` to it by hand. After the build passes, confirm the root layout got an opt-out (`grep -n "export const instant" <app dir>/layout.*`). The root layout renders every route, including framework routes like `/_not-found`, so if it was missed, add `export const instant = false` to it by hand.
Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor. Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor.
...@@ -147,7 +153,7 @@ Synthetic routes like `/_not-found` have no user file — when they block, fix t ...@@ -147,7 +153,7 @@ Synthetic routes like `/_not-found` have no user file — when they block, fix t
Incremental only. Stop here before starting step 2 — the pre-step is the shippable PR. Talk to the user in their language; don't say "Incremental" or other internal labels; talk about adoption, PRs, and what the app does now. Tell them: Incremental only. Stop here before starting step 2 — the pre-step is the shippable PR. Talk to the user in their language; don't say "Incremental" or other internal labels; talk about adoption, PRs, and what the app does now. Tell them:
- What you did: turned on Cache Components, ran the codemod that opts every page and layout out of the new validation (or did it by hand), fixed any blockers the codemod can't (list them), confirmed the build passes. - What you did: turned on Cache Components, ran the codemod that opts every page and layout out of the new validation (or did it by hand), fixed any blockers the codemod can't (list them), confirmed the build passes.
- What changed: every page and layout in `app/` now exports `instant = false` with a `// TODO: Cache Components adoption` comment, except client components and any that already had an `instant` export. - What changed: every page and layout in the app directory now exports `instant = false` with a `// TODO: Cache Components adoption` comment, except client components and any that already had an `instant` export.
- What to sanity-check: the diff is mostly mechanical (new exports + comments). The build passes. Routes still behave exactly as they did before — the opt-outs preserve current behavior; no rendering changes yet. - What to sanity-check: the diff is mostly mechanical (new exports + comments). The build passes. Routes still behave exactly as they did before — the opt-outs preserve current behavior; no rendering changes yet.
- The question: "Want to open this as its own PR before we start adopting Cache Components route by route? Or keep going on this branch?" Wait for the answer. - The question: "Want to open this as its own PR before we start adopting Cache Components route by route? Or keep going on this branch?" Wait for the answer.
...@@ -230,6 +236,6 @@ When the loop has run on every feature — every remaining `instant = false` sit ...@@ -230,6 +236,6 @@ When the loop has run on every feature — every remaining `instant = false` sit
The work below is optional and lives in the docs — link the user to them and let them decide which to take on next. Don't walk these through inside this skill. The work below is optional and lives in the docs — link the user to them and let them decide which to take on next. Don't walk these through inside this skill.
- [Sweep for more instant navigations](./references/dev-only-validations.md) — an optional follow-up once adoption is done, never required. A passing build is not the last word, because dev validates every route on each page load (simulating both page loads and client navigations) and catches what the build's first-error exit and descendant shadowing skipped. Offer it as the smaller path to instant navigation for a user who doesn't want to adopt Partial Prefetching. Adopting Partial Prefetching (below) runs the same kind of loop and meets these insights anyway, so recommend both and let the user pick which, or whether. The reference is the loop to execute. - [Sweep for more instant navigations](./references/dev-only-validations.md) — an optional follow-up once adoption is done, never required. A passing build is not the last word, because dev validates every route on each page load (simulating both page loads and client navigations) and catches what the build's first-error exit and descendant shadowing skipped. Offer it as the smaller path to instant navigation for a user who doesn't want to adopt Partial Prefetching. Adopting Partial Prefetching (below) runs the same kind of loop and meets these insights anyway, so recommend both and let the user pick which, or whether. The reference is the loop to execute.
- [`next-partial-prefetching-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-partial-prefetching-adoption) — the follow-up skill that adopts Partial Prefetching: it enables `partialPrefetching` and audits every `<Link prefetch={true}>` against a decision table (or adopts incrementally with the flag off, driven by the `link-prefetch-partial` insight). It sequences this the same way this skill sequences Cache Components, but the insights are dev-only, so it's a browser click-through, not a build loop. Recommended after instant navigation, since those fixes feed directly into how much of each route the shell can prefetch. Concepts live in the [Adopting Partial Prefetching guide](https://nextjs.org/docs/app/guides/adopting-partial-prefetching). - [`next-partial-prefetching-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-partial-prefetching-adoption) — the follow-up skill that adopts Partial Prefetching: it enables `partialPrefetching` and audits every `<Link prefetch={true}>` against a decision table (or adopts incrementally with the flag off, driven by the `instant-link-prefetch-partial` insight). It sequences this the same way this skill sequences Cache Components, but the insights are dev-only, so it's a browser click-through, not a build loop. Recommended after instant navigation, since those fixes feed directly into how much of each route the shell can prefetch. Concepts live in the [Adopting Partial Prefetching guide](https://nextjs.org/docs/app/guides/adopting-partial-prefetching).
- [Prevent regressions with e2e tests](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) — the `@next/playwright` [`instant()`](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#testing-instant-navigation) helper asserts on the UI that's available immediately on navigation, so regressions surface in CI. Recommend it once a route is instant: `next-dev-loop` confirms it _now_; an `instant()` test keeps it that way. - [Prevent regressions with e2e tests](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) — the `@next/playwright` [`instant()`](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#testing-instant-navigation) helper asserts on the UI that's available immediately on navigation, so regressions surface in CI. Recommend it once a route is instant: `next-dev-loop` confirms it _now_; an `instant()` test keeps it that way.
- [`next-cache-components-optimizer`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-optimizer) — a separate skill that grows each route's static shell so more of the page prerenders and less streams in. Pure optimization, not part of adoption. - [`next-cache-components-optimizer`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-optimizer) — a separate skill that grows each route's static shell so more of the page prerenders and less streams in. Pure optimization, not part of adoption.
...@@ -14,7 +14,7 @@ After the Cache Components build is clean, not before. While the app is mid-adop ...@@ -14,7 +14,7 @@ After the Cache Components build is clean, not before. While the app is mid-adop
Reuse the [`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) preflight (Turbopack), then add one job. On a webpack app, drive a browser directly with `agent-browser` or Playwright instead. You lose the `/_next/mcp` cross-checks, not the insights, which still show in the overlay and the dev log. Reuse the [`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) preflight (Turbopack), then add one job. On a webpack app, drive a browser directly with `agent-browser` or Playwright instead. You lose the `/_next/mcp` cross-checks, not the insights, which still show in the overlay and the dev log.
1. Build a route queue from the last build's route table or the `app/` tree. 1. Build a route queue from the last build's route table or the app directory.
2. Load each route in `next dev` with a browser. A refresh or a link click both work, and validation simulates both the page-load and client-navigation cases on that load, so you do not need to click through every link by hand. Dynamic params are checked against the real values you visit, so hit a concrete `[slug]`, not the pattern. 2. Load each route in `next dev` with a browser. A refresh or a link click both work, and validation simulates both the page-load and client-navigation cases on that load, so you do not need to click through every link by hand. Dynamic params are checked against the real values you visit, so hit a concrete `[slug]`, not the pattern.
3. Watch the dev log and the Insights tab. The dev log is the greppable record, one `Error: Route "...": Next.js encountered ...` line per insight with its `docs/messages/<slug>` link, and it reads the same on Turbopack and webpack. The Insights tab is amber and appears only once an insight fires, so a route with no tab is clean. Through `next-dev-loop`'s `/_next/mcp`, these come from `get_errors` and the overlay, not `get_request_insights`, which is the performance recorder and reports nothing here. 3. Watch the dev log and the Insights tab. The dev log is the greppable record, one `Error: Route "...": Next.js encountered ...` line per insight with its `docs/messages/<slug>` link, and it reads the same on Turbopack and webpack. The Insights tab is amber and appears only once an insight fires, so a route with no tab is clean. Through `next-dev-loop`'s `/_next/mcp`, these come from `get_errors` and the overlay, not `get_request_insights`, which is the performance recorder and reports nothing here.
4. Open the linked page for each distinct insight and apply its fix (usually pull a `<Suspense>` boundary down to the read). Reload to confirm it clears. 4. Open the linked page for each distinct insight and apply its fix (usually pull a `<Suspense>` boundary down to the read). Reload to confirm it clears.
......
...@@ -87,13 +87,11 @@ trustworthy. ...@@ -87,13 +87,11 @@ trustworthy.
## Reporting to the user ## Reporting to the user
This loop is meant to run unattended — ideally across many navigations in one This loop is meant to run unattended, so it doesn't stop to ask between steps.
pass — so it doesn't stop to ask after each route. If the user names one route, Work the navigation the user named, finish it, and stop. What matters is how you
finish it and stop. If they ask to make the app or its navigations instant, work word and present the results, not how often you interrupt. The mechanics below —
the whole route queue without pausing between routes. What matters is how you the rig, RED, GREEN, the gates — are your scaffolding; the user never needs to
word and present the results, not how often you hear those words.
interrupt. The mechanics below — the rig, RED, GREEN, the gates — are your
scaffolding; the user never needs to hear those words.
- **Speak their language.** Describe the gap and the result in terms of what the - **Speak their language.** Describe the gap and the result in terms of what the
user sees: "navigating to the dashboard waited on the charts query before user sees: "navigating to the dashboard waited on the charts query before
...@@ -108,8 +106,8 @@ scaffolding; the user never needs to hear those words. ...@@ -108,8 +106,8 @@ scaffolding; the user never needs to hear those words.
transcript of the loop. transcript of the loop.
- **Only surface a question for a genuine fork:** a fix that would change - **Only surface a question for a genuine fork:** a fix that would change
behavior, a security-sensitive read, or a route that's dynamic by design (a behavior, a security-sensitive read, or a route that's dynamic by design (a
runtime-prefetch candidate, not a shell to grow). A clean instant fix is not a per-link-prefetch candidate, not a shell to grow). A clean instant fix is not
fork — keep going. With no one to ask (an unattended run), don't block: take a fork — keep going. With no one to ask (an unattended run), don't block: take
the safe default and note the assumption — for a cache-freshness choice, the safe default and note the assumption — for a cache-freshness choice,
defer the read behind `<Suspense>` (always fresh, still instant) rather than defer the read behind `<Suspense>` (always fresh, still instant) rather than
guess a `cacheLife`. guess a `cacheLife`.
...@@ -371,10 +369,10 @@ this gate is as machine-checkable as the others. Detail: ...@@ -371,10 +369,10 @@ this gate is as machine-checkable as the others. Detail:
**When URL data can't be pushed down** (for example, the whole page depends on **When URL data can't be pushed down** (for example, the whole page depends on
`params`, `searchParams`, or the full URL), there may be no meaningful static `params`, `searchParams`, or the full URL), there may be no meaningful static
shell to grow. Don't force one. Runtime prefetching can make the soft shell to grow. Don't force one. Per-link prefetching can make the soft
navigation instant, but it is outside this optimizer loop: it requires Partial navigation instant, but it is outside this optimizer loop: it requires Partial
Prefetching, a `<Link prefetch={true}>`, and cached URL-dependent content. See Prefetching, a `<Link prefetch={true}>`, and cached URL-dependent content. See
[Runtime Prefetching](https://nextjs.org/docs/app/guides/runtime-prefetching) [Optimizing prefetching](https://nextjs.org/docs/app/guides/optimizing-prefetching)
and pattern 10 in `reference/patterns.md` for the requirements, cost trade-offs, and pattern 10 in `reference/patterns.md` for the requirements, cost trade-offs,
manual prefetch caveat, and `instant()` test gotchas. manual prefetch caveat, and `instant()` test gotchas.
...@@ -475,5 +473,5 @@ during an incremental rollout and keep checking any other target routes. ...@@ -475,5 +473,5 @@ during an incremental rollout and keep checking any other target routes.
That skill moves the app onto the better prefetching model: shared App Shell That skill moves the app onto the better prefetching model: shared App Shell
prefetches by default, fewer duplicated full-prefetch requests for visible prefetches by default, fewer duplicated full-prefetch requests for visible
links, a link audit for existing `<Link prefetch={true}>` usage, and optional links, a link audit for existing `<Link prefetch={true}>` usage, and optional
per-link runtime prefetching only where URL-specific content is worth the per-link prefetching only where URL-specific content is worth the
extra server work. extra server work.
...@@ -323,9 +323,9 @@ Prefer per-component boundaries inside the page (patterns #1–#5) over one big ...@@ -323,9 +323,9 @@ Prefer per-component boundaries inside the page (patterns #1–#5) over one big
Patterns 1–9 grow a **static shell** by moving dynamic reads behind boundaries. Session data from `cookies()` and `headers()` is handled by the earlier patterns. URL data is different: `params`, `searchParams`, and the full URL belong to one link, while the App Shell is shared by every link to the route. Patterns 1–9 grow a **static shell** by moving dynamic reads behind boundaries. Session data from `cookies()` and `headers()` is handled by the earlier patterns. URL data is different: `params`, `searchParams`, and the full URL belong to one link, while the App Shell is shared by every link to the route.
If the whole route depends on URL data, pushing the read lower may leave no meaningful shared shell to commit. That is the optimizer's stop point, not another shell refactor. Return to `SKILL.md` after the optimization loop for the optional runtime-prefetch follow-up. If the whole route depends on URL data, pushing the read lower may leave no meaningful shared shell to commit. That is the optimizer's stop point, not another shell refactor. Return to `SKILL.md` after the optimization loop for the optional per-link-prefetch follow-up.
Runtime prefetching is the only way for this soft navigation to commit the Per-link prefetching is the only way for this soft navigation to commit the
URL-specific content before the click. It has **three requirements**: URL-specific content before the click. It has **three requirements**:
```tsx ```tsx
...@@ -347,11 +347,11 @@ Under `instant()` the runtime entry is what commits, so the real content, not a ...@@ -347,11 +347,11 @@ Under `instant()` the runtime entry is what commits, so the real content, not a
Gotchas (each cost real debugging time): Gotchas (each cost real debugging time):
- **The full prefetch is mandatory.** With App Shells enabled an auto/PPR prefetch bails before the runtime spawn (`subtreeHasSpeculativePrefetch`); use `<Link prefetch={true}>` for normal links, or keep an existing manual full-prefetch abstraction if the app already owns one. If the route is still RED after caching the URL-dependent content, the navigation may still be doing an auto prefetch. - **The full prefetch is mandatory.** With App Shells enabled an auto/PPR prefetch bails before the runtime spawn (`subtreeHasSpeculativePrefetch`); use `<Link prefetch={true}>` for normal links, or keep an existing manual full-prefetch abstraction if the app already owns one. If the route is still RED after caching the URL-dependent content, the navigation may still be doing an auto prefetch.
- **Partial Prefetching must be adopted for the destination.** Runtime prefetching rides on the Partial Prefetching path. If the route is still RED after caching the URL-dependent content, check whether the link is still doing an auto prefetch or whether the destination never adopted Partial Prefetching. - **Partial Prefetching must be adopted for the destination.** Per-link prefetching uses the Partial Prefetching path. If the route is still RED after caching the URL-dependent content, check whether the link is still doing an auto prefetch or whether the destination never adopted Partial Prefetching.
- **Prefetch the canonical URL.** A link whose href 307-redirects (a `/foo` that canonicalizes to `/`) can't be prefetched — the prefetch receives the redirect, not the tree. Point the link and the prefetch at the final URL. - **Prefetch the canonical URL.** A link whose href 307-redirects (a `/foo` that canonicalizes to `/`) can't be prefetched — the prefetch receives the redirect, not the tree. Point the link and the prefetch at the final URL.
- **Don't blanket the full prefetch.** It fetches _all_ the target's dynamic data; enabling it for every visible link is wasteful. Scope `prefetch={true}` to the runtime-prefetch targets only, using the [runtime prefetching trade-offs](https://nextjs.org/docs/app/guides/runtime-prefetching#per-link-prefetching-trade-offs) and [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) when many links are visible. - **Don't blanket the full prefetch.** It fetches _all_ the target's dynamic data; enabling it for every visible link is wasteful. Scope `prefetch={true}` to the per-link-prefetch targets only, using the [trade-offs](https://nextjs.org/docs/app/guides/optimizing-prefetching#trade-offs) and [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) when many links are visible.
- **Marker must be a committed node, not RSC bytes.** The content is often a client component, so its text isn't in the prefetch response — assert a `data-testid` that renders when the client subtree commits, not a substring of the stream. - **Marker must be a committed node, not RSC bytes.** The content is often a client component, so its text isn't in the prefetch response — assert a `data-testid` that renders when the client subtree commits, not a substring of the stream.
Prefer a static shell (patterns 1–9) whenever the URL-data read can move: it's cheaper than a runtime prefetch and also covers hard load. Runtime prefetching is only for URL-data reads that genuinely can't move, or routes whose useful content is all URL-specific. Prefer a static shell (patterns 1–9) whenever the URL-data read can move: it's cheaper than a per-link prefetch and also covers hard load. Per-link prefetching is only for URL-data reads that genuinely can't move, or routes whose useful content is all URL-specific.
**Insight:** [dynamic data during prefetching](https://nextjs.org/docs/messages/instant-link-prefetch-partial). **Insight:** [dynamic data during prefetching](https://nextjs.org/docs/messages/instant-link-prefetch-partial).
...@@ -76,7 +76,7 @@ The shell prerenders as if authorized (the session read suspends before `redirec ...@@ -76,7 +76,7 @@ The shell prerenders as if authorized (the session read suspends before `redirec
## Initial-load shell vs soft-navigation shell ## Initial-load shell vs soft-navigation shell
The `test-template.md` specs drive a `<Link>` click for soft navigations and `page.goto()` for initial loads. The two shells can differ for the same route: The `../test-template.md` specs drive a `<Link>` click for soft navigations and `page.goto()` for initial loads. The two shells can differ for the same route:
> **The initial-load shell can show less than the soft-navigation shell when a layout above the shared boundary awaits un-enumerated `params`/`searchParams`.** An initial load re-runs every layout from the root; if a parent layout does `await props.params` and that segment has no `generateStaticParams`, the param suspends on the initial load and its whole subtree drops out of the shell. A soft navigation does not re-render that parent and already has the params. Symptom: an element present after a `<Link>` click is missing after `goto`. > **The initial-load shell can show less than the soft-navigation shell when a layout above the shared boundary awaits un-enumerated `params`/`searchParams`.** An initial load re-runs every layout from the root; if a parent layout does `await props.params` and that segment has no `generateStaticParams`, the param suspends on the initial load and its whole subtree drops out of the shell. A soft navigation does not re-render that parent and already has the params. Symptom: an element present after a `<Link>` click is missing after `goto`.
......
...@@ -139,7 +139,7 @@ Two defenses; use both: ...@@ -139,7 +139,7 @@ Two defenses; use both:
(SKILL.md phases 0 and A). Do not trust a pass from a build where it is not set. (SKILL.md phases 0 and A). Do not trust a pass from a build where it is not set.
2. **Make the test self-validating**: for any route with deferred content, also assert that the 2. **Make the test self-validating**: for any route with deferred content, also assert that the
deferred content is gated under the lock, not only that the shell is present deferred content is gated under the lock, not only that the shell is present
(`test-template.md`, self-validating variant). If the lock did not engage, the content is (`../test-template.md`, self-validating variant). If the lock did not engage, the content is
already present and `toHaveCount(0)` fails. already present and `toHaveCount(0)` fails.
The gated half holds under the lock for both navigation types regardless of warm state: the The gated half holds under the lock for both navigation types regardless of warm state: the
......
...@@ -82,7 +82,9 @@ Once per session, confirm both views are live. ...@@ -82,7 +82,9 @@ Once per session, confirm both views are live.
the next `open` restores it. the next `open` restores it.
2. Probe `/_next/mcp` (`tools/list`) — confirm it's reachable and 2. Probe `/_next/mcp` (`tools/list`) — confirm it's reachable and
lists `get_compilation_issues`: lists `get_compilation_issues`. First read the port off the
`next dev` banner; if it isn't 3000, set
`NEXT_MCP_URL=http://localhost:<port>/_next/mcp` before probing:
- Unreachable → either `next dev` isn't running, or Next.js is - Unreachable → either `next dev` isn't running, or Next.js is
below 16.3. Check `package.json` to disambiguate, then refuse. below 16.3. Check `package.json` to disambiguate, then refuse.
- `get_compilation_issues` not in the list → Next.js below 16.3. - `get_compilation_issues` not in the list → Next.js below 16.3.
...@@ -149,8 +151,6 @@ manual rather than from memory. ...@@ -149,8 +151,6 @@ manual rather than from memory.
- `/_next/mcp` replies are SSE — read the JSON off the `data:` line - `/_next/mcp` replies are SSE — read the JSON off the `data:` line
with `sed -n 's/^data: //p'` (a plain `sed 's/^data: //'` leaves the with `sed -n 's/^data: //p'` (a plain `sed 's/^data: //'` leaves the
`event:` line and the parse fails). `event:` line and the parse fails).
- Non-3000 dev server: read the `next dev` banner; set
`NEXT_MCP_URL=http://localhost:<port>/_next/mcp`.
- `get_errors` and `get_page_metadata` need at least one navigation - `get_errors` and `get_page_metadata` need at least one navigation
to populate. to populate.
...@@ -181,8 +181,3 @@ Close the session with the same session and restore context: ...@@ -181,8 +181,3 @@ Close the session with the same session and restore context:
`agent-browser --session "$SESSION" --restore close`. `close` saves `agent-browser --session "$SESSION" --restore close`. `close` saves
that session's cookies and storage so the next loop's `--restore` open that session's cookies and storage so the next loop's `--restore` open
keeps the user logged in. Leave `next dev` up for the next loop. keeps the user logged in. Leave `next dev` up for the next loop.
---
`next-dev-loop-<topic>` siblings (e.g. `next-dev-loop-rsc`, `next-dev-loop-debug`)
assume this preflight already ran; they pick up at the loop.
...@@ -6,7 +6,7 @@ description: > ...@@ -6,7 +6,7 @@ description: >
Partial Prefetching, flip the `partialPrefetching` flag, opt routes Partial Prefetching, flip the `partialPrefetching` flag, opt routes
in with `export const prefetch = 'partial'`, audit in with `export const prefetch = 'partial'`, audit
`<Link prefetch={true}>` calls, or resolve the `<Link prefetch={true}>` calls, or resolve the
link-prefetch-partial and instant-shell-url-data insights. instant-link-prefetch-partial and instant-shell-url-data insights.
--- ---
# next-partial-prefetching-adoption # next-partial-prefetching-adoption
...@@ -23,7 +23,7 @@ Talk to the user in terms of what they'll see — PRs, features, and how the app ...@@ -23,7 +23,7 @@ Talk to the user in terms of what they'll see — PRs, features, and how the app
- **Next.js 16.3 or later.** `partialPrefetching`, the `prefetch` route segment config, and the prefetch insights all land there. - **Next.js 16.3 or later.** `partialPrefetching`, the `prefetch` route segment config, and the prefetch insights all land there.
- **A browser you can drive.** Install [`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) before starting (`npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop`). Install it without asking — it's a tool, not a product change — and don't assume it's blocked: verify a real blocker (no network, no npm, read-only filesystem) before falling back, and name it in your report. Link prefetches fire when a link renders and enters the viewport, and shell validation fires on navigation — neither is reachable from `curl` or the build. If the app is webpack-pinned, drive a browser directly (`agent-browser`, Playwright) — you lose the framework cross-checks, not the insights; they're still in the overlay and the dev log. - **A browser you can drive.** Install [`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) before starting, unless it is already available — it ships alongside this skill (`npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop`). Install it without asking — it's a tool, not a product change — and don't assume it's blocked: verify a real blocker (no network, no npm, read-only filesystem) before falling back, and name it in your report. Link prefetches fire when a link renders and enters the viewport, and shell validation fires on navigation — neither is reachable from `curl` or the build. If the app is webpack-pinned, drive a browser directly (`agent-browser`, Playwright) — you lose the framework cross-checks, not the insights; they're still in the overlay and the dev log.
- **A runnable app.** Verification runs against `next dev` for the insight sweep and a production `next build`/`next start` for prefetching (prefetching is prod-only), so the app has to boot in both. If it reads a database or required env at import (e.g. an `env.ts` that throws on a missing `DATABASE_URL`), confirm it starts — with the real environment, or local data you stand up — before step 1. An app that won't run can't be swept or verified. - **A runnable app.** Verification runs against `next dev` for the insight sweep and a production `next build`/`next start` for prefetching (prefetching is prod-only), so the app has to boot in both. If it reads a database or required env at import (e.g. an `env.ts` that throws on a missing `DATABASE_URL`), confirm it starts — with the real environment, or local data you stand up — before step 1. An app that won't run can't be swept or verified.
...@@ -49,18 +49,18 @@ Every insight has a docs page — open it. Fetch the linked page for every disti ...@@ -49,18 +49,18 @@ Every insight has a docs page — open it. Fetch the linked page for every disti
## step 1: audit `<Link prefetch={true}>` (before enabling) ## step 1: audit `<Link prefetch={true}>` (before enabling)
If `partialPrefetching: true` is already set in `next.config.ts`, the app is adopted — skip to [step 3](#step-3-sweep-for-url-data-insights-after-enabling). Otherwise work the audit with the global flag **off**, adopting each destination with `export const prefetch = 'partial'` — enabling the flag first would mark every route adopted and silence the [`link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) insight this audit runs on. Ask the user how to ship it, in the language of PRs: If `partialPrefetching: true` is already set in `next.config.ts`, the app is adopted — skip to [step 3](#step-3-sweep-for-url-data-insights-after-enabling). Otherwise work the audit with the global flag **off**, adopting each destination with `export const prefetch = 'partial'` — enabling the flag first would mark every route adopted and silence the [`instant-link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) insight this audit runs on. Ask the user how to ship it, in the language of PRs:
- **One branch** — the whole audit in one change, with the flag enabled and the codemod run at the end (step 2). - **One branch** — the whole audit in one change, with the flag enabled and the codemod run at the end (step 2).
- **Route by route** — each adopted destination ships as its own PR. The insight still fires for the destinations you haven't reached, a live worklist, and step 2 comes after the last one. - **Route by route** — each adopted destination ships as its own PR. The insight still fires for the destinations you haven't reached, a live worklist, and step 2 comes after the last one.
The work is identical either way — only the commit boundaries differ. Default by app size: one branch for a handful of links, route by route when the audit is big enough that reviewers need smaller diffs. Note the choice in your report. The work is identical either way — only the commit boundaries differ. Default by app size: one branch for a handful of links, route by route when the audit is big enough that reviewers need smaller diffs. Note the choice in your report.
Enumerate the prefetch sites across the whole source tree, not only `app/` — they often live in `src/components` or shared UI packages: `rg -n '\bprefetch\b|router\.prefetch' -g '*.tsx' -g '*.jsx' .`. Keep the `<Link prefetch={true}>` and bare-prop matches (a bare prop is `true`) as the over-prefetching links this audit adopts destinations for, and drop `prefetch={false}` and other values. Also audit existing imperative [`router.prefetch()`](https://nextjs.org/docs/app/api-reference/functions/use-router#userouter) call sites with the same table, because they can be preserving the same "fetch before navigation" behavior and have no dev insight. For new navigation prefetching, prefer [`<Link>`](https://nextjs.org/docs/app/api-reference/components/link), which the docs call the primary navigation API; use [`router.prefetch()`](https://nextjs.org/docs/app/guides/prefetching#manual-prefetch) only for manual prefetching. If the app already passes an internal `kind` option, treat that as existing implementation detail, not a pattern to spread. If nothing matches, check for a custom link wrapper before calling the audit empty. If there's still nothing, say so in your report and move on to [step 2](#step-2-enable-the-flag). Enumerate the prefetch sites across the whole source tree, not only `app/` — they often live in `src/components` or shared UI packages: `rg -n '\bprefetch\b|router\.prefetch' -g '*.tsx' -g '*.jsx' .`. Keep the `<Link prefetch={true}>` and bare-prop matches (a bare prop is `true`) as the over-prefetching links this audit adopts destinations for, and drop `prefetch={false}` and other values. Also audit existing imperative [`router.prefetch()`](https://nextjs.org/docs/app/api-reference/functions/use-router#userouter) call sites with the same table, because they can be preserving the same "fetch before navigation" behavior and have no dev insight. For new navigation prefetching, prefer [`<Link>`](https://nextjs.org/docs/app/api-reference/components/link), which the docs call the primary navigation API; use [`router.prefetch()`](https://nextjs.org/docs/app/guides/prefetching#manual-prefetch) only for manual prefetching. If the app already passes an internal `kind` option, treat that as existing implementation detail, not a pattern to spread. Always inspect custom Link wrappers and trace their consumers: a wrapper can call `router.prefetch()` on hover or touch while a consumer omits `prefetch` or passes `prefetch={false}`. Record the declarative and imperative behavior separately, and use keyboard activation when verifying the declarative path so hover prefetching does not mask it. If nothing matches, say so in your report and move on to [step 2](#step-2-enable-the-flag).
Then, for each one: Then, for each one:
1. **Click each `<Link>` in `next dev`.** The insight fires at navigation time, not when the link prefetches, so a link sitting in the viewport won't trip it — you have to navigate through it. This click is _verification_: it confirms the insight fires before you adopt and clears after. Imperative `router.prefetch()` sites have no equivalent insight, so audit them from source and verify them in production ([step 4](#step-4-verify)). Without a browser, skip the click and adopt from [`link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) and the audit table below — the destination's structure tells you the row, and type-check gates the edit — then leave the live confirmation for the hand-off. 1. **Click each `<Link>` in `next dev`.** The insight fires at navigation time, not when the link prefetches, so a link sitting in the viewport won't trip it — you have to navigate through it. This click is _verification_: it confirms the insight fires before you adopt and clears after. Imperative `router.prefetch()` sites have no equivalent insight, so audit them from source and verify them in production ([step 4](#step-4-verify)). Without a browser, skip the click and adopt from [`instant-link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) and the audit table below — the destination's structure tells you the row, and type-check gates the edit — then leave the live confirmation for the hand-off.
2. **Adopt the destination.** Add the temporary route config with a link to the migration guide. That clears the insight for every link pointing at it: 2. **Adopt the destination.** Add the temporary route config with a link to the migration guide. That clears the insight for every link pointing at it:
```tsx ```tsx
...@@ -68,11 +68,11 @@ Then, for each one: ...@@ -68,11 +68,11 @@ Then, for each one:
export const prefetch = 'partial' export const prefetch = 'partial'
``` ```
If the route reads URL data (`params`, `searchParams`), the default link still warms only its skeleton (the guide's [URL data](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#url-data) section), so it's a runtime-prefetch candidate for step 5, not a finished adoption. Keep `prefetch={true}` on its links and mark the route: If the route reads URL data (`params`, `searchParams`), the default link still warms only its skeleton (the guide's [URL data](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#url-data) section), so it's a per-link-prefetch candidate for step 5, not a finished adoption. Keep `prefetch={true}` on its links and mark the route:
```tsx ```tsx
// TODO(runtime-prefetch): assess with the user whether URL data should resolve before click. // TODO(per-link-prefetch): assess with the user whether URL data should resolve before click.
// See: https://nextjs.org/docs/app/guides/runtime-prefetching // See: https://nextjs.org/docs/app/guides/optimizing-prefetching
export const prefetch = 'partial' export const prefetch = 'partial'
``` ```
...@@ -80,6 +80,8 @@ Then, for each one: ...@@ -80,6 +80,8 @@ Then, for each one:
3. **Preserve what that prefetch delivered.** The guide's [audit table](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#auditing-link-prefetchtrue-calls) is the canonical decision — fetch it and apply the matching row. Caching uncached content is the judgment call in that table: trace where the data comes from and what freshness and revalidation it needs, per the [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache) docs, and ask the user when the answer isn't clear-cut. The URL-data routes you marked in the previous item wait for step 5. 3. **Preserve what that prefetch delivered.** The guide's [audit table](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#auditing-link-prefetchtrue-calls) is the canonical decision — fetch it and apply the matching row. Caching uncached content is the judgment call in that table: trace where the data comes from and what freshness and revalidation it needs, per the [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache) docs, and ask the user when the answer isn't clear-cut. The URL-data routes you marked in the previous item wait for step 5.
If the repository already has `instant()` e2e coverage for a destination, run it before editing and preserve its assertion as the contract. A successful build or completed navigation does not prove that the same UI was prefetched. If caching the primary data loader still leaves only a fallback inside `instant()`, inspect rendered descendants and providers for dynamic work, then expand the cache only to the smallest coherent rendered subtree that restores the contract.
> **If you add `use cache`, verify under `next start`, not only the build.** A `cookies()`/`headers()`/session read anywhere in the cached call tree throws at request time while `next build` passes clean. See [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache). > **If you add `use cache`, verify under `next start`, not only the build.** A `cookies()`/`headers()`/session read anywhere in the cached call tree throws at request time while `next build` passes clean. See [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache).
## step 2: enable the flag ## step 2: enable the flag
...@@ -87,13 +89,13 @@ Then, for each one: ...@@ -87,13 +89,13 @@ Then, for each one:
Once every audited destination has `prefetch = 'partial'`, finish in two moves. Once every audited destination has `prefetch = 'partial'`, finish in two moves.
1. **Enable the flag globally.** Set `partialPrefetching: true` in `next.config.ts` (alongside `cacheComponents: true`). Every route is adopted now, so every link is good. 1. **Enable the flag globally.** Set `partialPrefetching: true` in `next.config.ts` (alongside `cacheComponents: true`). Every route is adopted now, so every link is good.
2. **Strip the redundant `prefetch = 'partial'` exports.** Run the first-party `remove-partial-prefetch` codemod rather than a text find-and-replace. It removes only `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment. It leaves other values such as `prefetch = 'force-disabled'` in place, along with your `TODO(runtime-prefetch)` markers and their Runtime Prefetching guide links, which wait for step 5. 2. **Strip the redundant `prefetch = 'partial'` exports.** Run the first-party `remove-partial-prefetch` codemod rather than a text find-and-replace. It removes only `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment. It leaves other values such as `prefetch = 'force-disabled'` in place, along with your `TODO(per-link-prefetch)` markers and their Optimizing prefetching guide links, which wait for step 5.
```bash ```bash
npx @next/codemod@latest remove-partial-prefetch ./app npx @next/codemod@latest remove-partial-prefetch ./app
``` ```
The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand by removing `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment from every `app/**/{page,layout}.{js,jsx,ts,tsx}` — leave other `prefetch` values in place, and leave the `TODO(runtime-prefetch)` markers and Runtime Prefetching guide links where they are. Don't hand-edit when the codemod can run. The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand by removing `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment from every `app/**/{page,layout}.{js,jsx,ts,tsx}` — leave other `prefetch` values in place, and leave the `TODO(per-link-prefetch)` markers and Optimizing prefetching guide links where they are. Don't hand-edit when the codemod can run.
## step 3: sweep for URL-data insights (after enabling) ## step 3: sweep for URL-data insights (after enabling)
...@@ -116,24 +118,24 @@ Checklist before checking in with the user: ...@@ -116,24 +118,24 @@ Checklist before checking in with the user:
- **An empty sweep is expected when Cache Components adoption finished cleanly.** A quiet log is success, not a missing signal. If you deliberately probe the validation path, use a `generateStaticParams` route with `params` read inside `<Suspense>` but before the URL-specific leaf boundary; other shapes may surface `blocking-prerender-*` instead. - **An empty sweep is expected when Cache Components adoption finished cleanly.** A quiet log is success, not a missing signal. If you deliberately probe the validation path, use a `generateStaticParams` route with `params` read inside `<Suspense>` but before the URL-specific leaf boundary; other shapes may surface `blocking-prerender-*` instead.
- The App Shells are real: for each route you changed, confirm the first paint after a navigation shows the intended shared content, not an empty shell or a stuck fallback. A `<Suspense>` around the whole page body passes validation with an empty shell, which defeats the point. - The App Shells are real: for each route you changed, confirm the first paint after a navigation shows the intended shared content, not an empty shell or a stuck fallback. A `<Suspense>` around the whole page body passes validation with an empty shell, which defeats the point.
- The insights validate shell _structure_, not that a prefetch actually happened. Confirm on the production run (prefetching is prod-only) that navigating a changed link lands on the shared shell instantly. - The insights validate shell _structure_, not that a prefetch actually happened. Confirm on the production run (prefetching is prod-only) that navigating a changed link lands on the shared shell instantly.
- **If the app prefetches imperatively**, the insight sweep does not cover it, so an empty sweep is not proof the prefetch survived the flag. Verify the call under `next start`: compare the `_rsc` prefetch response or resource timing before/after, and make sure any intentionally preserved full prefetch still carries the data the old call was warming. If it now returns only the App Shell, migrate that call site using the same decision as the nearest `<Link prefetch={true}>` destination — cache the data, or move runtime-prefetch behavior to a docs-supported `<Link prefetch={true}>`. - **If the app prefetches imperatively**, the insight sweep does not cover it, so an empty sweep is not proof the prefetch survived the flag. Verify the call under `next start`: compare the `_rsc` prefetch response or resource timing before/after, and make sure any intentionally preserved full prefetch still carries the data the old call was warming. If it now returns only the App Shell, migrate that call site using the same decision as the nearest `<Link prefetch={true}>` destination — cache the data, or move per-link-prefetch behavior to a docs-supported `<Link prefetch={true}>`.
- **Before blaming a broken route on the flag, reproduce it with `partialPrefetching` off** (or on the pre-flag branch). The flag surfaces existing issues — a fragile request-time auth gate, a rewrite, deployment skew — earlier and more visibly, but rarely causes them. If it breaks flag-off too, it isn't a Partial Prefetching problem; fix it there, not here. - **Before blaming a broken route on the flag, reproduce it with `partialPrefetching` off** (or on the pre-flag branch). The flag surfaces existing issues — a fragile request-time auth gate, a rewrite, deployment skew — earlier and more visibly, but rarely causes them. If it breaks flag-off too, it isn't a Partial Prefetching problem; fix it there, not here.
- `next build` still passes. - `next build` still passes.
Then check in with the user. Speak their language — no insight slugs or step labels. Then check in with the user. Speak their language — no insight slugs or step labels.
- What you did: which links you audited, which destinations you adopted, and what each link now prefetches. - What you did: which links you audited, which destinations you adopted, and what each link now prefetches.
- What changed: dropped props, `use cache` boundaries added, and which routes carry a `TODO(runtime-prefetch)` marker for later. - What changed: dropped props, `use cache` boundaries added, and which routes carry a `TODO(per-link-prefetch)` marker for later.
- Demo against a production run. Prefetching is limited in development, so `next dev` won't show the result — run `next build` and `next start`, and hand the user that URL. That run needs the app's real environment (database, auth, secrets), and a partial or stale install or leftover generated artifacts can fail the build for reasons unrelated to the adoption. Set the expectation up front that verification is a complete, credentialed production run, not a quick check. - Demo against a production run. Prefetching is limited in development, so `next dev` won't show the result — run `next build` and `next start`, and hand the user that URL. That run needs the app's real environment (database, auth, secrets), and a partial or stale install or leftover generated artifacts can fail the build for reasons unrelated to the adoption. Set the expectation up front that verification is a complete, credentialed production run, not a quick check.
- Show, don't tell: drive one link live in the headed browser against the production server, so they see the shared App Shell paint instantly and the URL-specific region stream in. Attach before/after screenshots only when a live browser isn't possible. - Show, don't tell: drive one link live in the headed browser against the production server, so they see the shared App Shell paint instantly and the URL-specific region stream in. Attach before/after screenshots only when a live browser isn't possible.
- Give them the click-through: a table of each changed route — the link to click, and what to expect after the click (what paints instantly, what streams in) — so they can verify each result themselves. - Give them the click-through: a table of each changed route — the link to click, and what to expect after the click (what paints instantly, what streams in) — so they can verify each result themselves.
- The question: "Want to commit this (or open the PR) before we look at which routes should also prefetch their URL-specific content?" Wait for the answer — adoption and runtime prefetching read best as their own changes. - The question: "Want to commit this (or open the PR) before we look at which routes should also prefetch their URL-specific content?" Wait for the answer — adoption and per-link prefetching read best as their own changes.
## step 5: runtime prefetching (optional) ## step 5: per-link prefetching (optional)
The audit marked the candidates instead of deciding them. Grep for `TODO(runtime-prefetch)` and walk the list with the user in one conversation. The question per route is whether they want the URL-dependent content prefetched ahead of the click, or streaming in after navigation is fine. A runtime prefetch costs a server invocation per prefetchable link — the guide's [per-link prefetching trade-offs](https://nextjs.org/docs/app/guides/runtime-prefetching#per-link-prefetching-trade-offs) section is the checklist. Don't make these calls alone. The audit marked the candidates instead of deciding them. Grep for `TODO(per-link-prefetch)` and walk the list with the user in one conversation. The question per route is whether they want the URL-dependent content prefetched ahead of the click, or streaming in after navigation is fine. A per-link prefetch costs a server invocation per prefetchable link — the guide's [trade-offs](https://nextjs.org/docs/app/guides/optimizing-prefetching#trade-offs) section is the checklist. Don't make these calls alone.
Where the answer is yes, follow the [runtime prefetching guide](https://nextjs.org/docs/app/guides/runtime-prefetching): keep [`<Link prefetch={true}>`](https://nextjs.org/docs/app/api-reference/components/link#prefetch) on the links that should resolve more than the App Shell, and cache the content behind the URL-data read using the guide's patterns (`use cache` with the runtime value passed in, or `use cache: private` for per-user data). Each per-link prefetch is a server render when the destination needs non-static data, so use the guide's [per-link trade-offs](https://nextjs.org/docs/app/guides/runtime-prefetching#per-link-prefetching-trade-offs) to decide when viewport prefetching is worth it and when [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) is a better fit. Where it's no, delete the marker and leave the route on the App Shell default. Either way no `TODO(runtime-prefetch)` marker survives this step. Confirm the opted-in links against a production run (`next build` and `next start` — the runtime prefetch fires there, not in `next dev`), give the user the same click-through for them, and keep this as its own commit or PR. Where the answer is yes, follow the [Optimizing prefetching guide](https://nextjs.org/docs/app/guides/optimizing-prefetching): keep [`<Link prefetch={true}>`](https://nextjs.org/docs/app/api-reference/components/link#prefetch) on the links that should resolve more than the App Shell, and cache the content behind the URL-data read using the guide's patterns (`use cache` with the runtime value passed in, or `use cache: private` for per-user data). Each per-link prefetch is a server render when the destination needs non-static data, so use the guide's [per-link trade-offs](https://nextjs.org/docs/app/guides/optimizing-prefetching#trade-offs) to decide when viewport prefetching is worth it and when [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) is a better fit. Where it's no, delete the marker and leave the route on the App Shell default. Either way no `TODO(per-link-prefetch)` marker survives this step. Confirm the opted-in links against a production run (`next build` and `next start` — the per-link prefetch runs there, not in `next dev`), give the user the same click-through for them, and keep this as its own commit or PR.
## further reading ## further reading
......
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