Unverified Commit ab4b1918 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs(cache-components): clarify allow-runtime, sync-IO and instant=false, CLS fallback (#94997)

### What?

Docs-only follow-ups for Cache Components and Partial Prefetching, from
agent migration friction logs and Joseph's review of
[#95082](https://github.com/vercel/next.js/pull/95082).

- **`adopting-partial-prefetching.mdx`** — reframe the `allow-runtime`
row in the audit table (it's an enhancement, not the `<Link
prefetch={true}>` warning fix; the per-route opt-in is `prefetch =
'partial'`).
- **`migrating-to-cache-components.mdx`** — split the `## Enable Cache
Components` section into before-flag (remove `dynamic` / `revalidate` /
`fetchCache`) and after-flag (translate `revalidate`, `fetchCache`,
`unstable_cache`, `fetch` cache options) steps. Flag the `revalidateTag`
second-argument requirement, with a Before / After example. Add two
Good-to-know callouts: off-grid `revalidate` values map to the closest
`cacheLife` profile; `instant = false` is allowed-to-block, not
forced-dynamic.
- **`blocking-prerender-current-time` / `-random` / `-crypto`** (and
their `-client` siblings) — drop the misleading "Don't want this
validation?" opt-out section. `instant = false` is an instant-navigation
knob and doesn't suppress sync-IO prerender errors.
- **Remaining `blocking-prerender-*` pages** — standardize the CLS
fallback callout so they all link the canonical section.

### Why?

Friction logs surfaced four recurring misreads:

1. Devs expected `prefetch = 'allow-runtime'` to silence the `<Link
prefetch={true}>` warning. The docs implied it would.
2. The migration guide mixed `dynamic` removal with `unstable_cache`
translation, so it wasn't clear which had to happen before the flag and
which after.
3. `revalidateTag` now requires a cache profile, but the on-demand
revalidation section didn't say so.
4. Sync-IO error pages still carried a "Don't want this validation?"
opt-out that doesn't actually work for those errors.
parent 70e3934f
......@@ -75,6 +75,8 @@ export default function Page() {
A `<Link>` pointing at a route with `prefetch = 'partial'` loads the App Shell only, even when `partialPrefetching` is not set in `next.config.ts`.
> **Good to know**: Adopting per-route first also preserves the dev-only `<Link prefetch={true}>` warning, which points at `<Link prefetch={true}>` calls whose destinations haven't adopted yet. Enabling the global flag first marks every route as adopted, which silences the warning and removes the signal for the [audit below](#auditing-existing-link-prefetchtrue-calls).
Once every route in scope has `prefetch = 'partial'`, enable the config and remove the per-route exports:
```ts filename="next.config.ts" highlight={5}
......@@ -94,11 +96,13 @@ When `partialPrefetching` is enabled, `<Link prefetch={true}>` now prefetches th
Previously, `<Link prefetch={true}>` also prefetched dynamic data.
| Destination | Recommendation |
| ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Fully static (no `"use cache"`, no Suspense) | Drop `prefetch={true}`. The default `<Link>` already loads the full page because the App Shell is the page. |
| Has cached content worth shipping ahead of the click | Keep `prefetch={true}`. The cached parts come with the App Shell. |
| Reads request data (`cookies()`, `headers()`, `searchParams`) the user will need on arrival | Keep `prefetch={true}` and opt the route into [runtime prefetching](/docs/app/guides/runtime-prefetching) with `prefetch = 'allow-runtime'`. |
| Destination | Recommendation |
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Fully static (no `"use cache"`, no Suspense) | Drop `prefetch={true}`. The default `<Link>` already loads the full page because the App Shell is the page. |
| Has cached content worth shipping ahead of the click | Keep `prefetch={true}`. The cached parts come with the App Shell. |
| Reads request data (`cookies()`, `headers()`, `searchParams`) the user will need on arrival | Keep `prefetch={true}`. Optionally enhance it with [runtime prefetching](/docs/app/guides/runtime-prefetching) (`prefetch = 'allow-runtime'`) so the request data is prefetched too. |
> **Good to know**: `prefetch = 'allow-runtime'` is an _enhancement_ that adds runtime prefetching of request data. It is not a way to silence the dev `<Link prefetch={true}>` warning. That warning means the link does a legacy full prefetch of a route that hasn't adopted Partial Prefetching. The per-route opt-in for Partial Prefetching is `prefetch = 'partial'`, which is separate from `'allow-runtime'`.
Before:
......
......@@ -53,6 +53,8 @@ export default nextConfig
> **Good to know:** If you were using `experimental.dynamicIO` or `experimental.useCache`, `cacheComponents` replaces them. See the [version 16 upgrade guide](/docs/app/guides/upgrading/version-16#experimentaldynamicio-and-experimentalusecache).
After enabling the flag, route segments that still export `dynamic`, `revalidate`, or `fetchCache` will error. Start by replacing those configs. The sections below explain what to do for each one.
## `dynamic = "force-dynamic"`
**Not needed.** All pages are dynamic by default.
......@@ -185,6 +187,8 @@ export default async function Page() {
}
```
> **Good to know**: If your `revalidate` value doesn't match a built-in [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile (`'seconds'`, `'minutes'`, `'hours'`, `'days'`, `'weeks'`, `'max'`), pick the closest one or define a [custom profile](/docs/app/api-reference/functions/cacheLife#custom-cache-profiles).
## `fetchCache`
**Not needed.** With `use cache`, all data fetching within a cached scope is automatically cached, making `fetchCache` unnecessary.
......@@ -247,6 +251,8 @@ Cache Components validates your routes in development and surfaces errors and in
Each card is clickable and opens a page with patterns, code samples, and trade-offs. Work through the insights and errors until they're gone. For the full validation workflow, the DevTools, and CI testing, see the [instant navigation guide](/docs/app/guides/instant-navigation).
Insights don't show up in the HTTP response. An offending route still returns `200` with rendered HTML in dev. The insight only appears in the dev overlay, the dev-server log, or the [MCP `get_errors` tool](/docs/app/guides/mcp). To see them, read the overlay (or query the MCP).
## Opting out of validation
A validation insight or error tells you a route won't render instantly. Resolve it by following the recommendation: cache the data with [`use cache`](/docs/app/api-reference/directives/use-cache) or wrap it in [`<Suspense>`](https://react.dev/reference/react/Suspense). If you're not ready to address it yet, set the [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) config to `false` on the segment that raised it (a layout, page, or parallel slot), then come back to it later.
......@@ -255,6 +261,8 @@ A validation insight or error tells you a route won't render instantly. Resolve
export const instant = false
```
> **Good to know**: `instant = false` marks a segment as _allowed to block_. It does not force the route to be dynamic, so a genuinely prerenderable route still ships a static shell. It also does not clear synchronous-IO build errors: calls like `new Date()`, `Math.random()`, and `crypto.randomUUID()` still fail the prerender. Fix those with the cards Next.js shows for each error.
## `fetch` cache options
**Move `cache` and `next` options to `use cache`.**
......@@ -396,7 +404,7 @@ Like the `fetch` Data Cache, `unstable_cache` persists cached values across depl
On-demand invalidation still works by tagging cached data and expiring it after an event. Tag data with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) inside a `use cache` function instead of the `fetch` `next.tags` option, then choose the invalidation API by the behavior you want:
- [`updateTag`](/docs/app/api-reference/functions/updateTag): for mutations whose result the user must see immediately (read-your-own-writes). Called from a Server Action, it expires the tag so the next request waits for fresh data instead of serving stale content.
- [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag): for stale-while-revalidate. Pass a cache profile like `'max'` to serve cached data while it refreshes in the background. Works in Server Actions and Route Handlers.
- [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag): for stale-while-revalidate. A cache profile is **required** as the second argument, for example use `'max'` to serve cached data while it refreshes in the background. Works in Server Actions and Route Handlers.
- [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath): unchanged from the previous caching model.
`updateTag` isn't exclusive to Cache Components (it also works with the previous caching model), but migrating is a good time to adopt it. After a mutation in a Server Action, reach for it when the user should see their own change right away.
......@@ -421,7 +429,49 @@ export async function createPost(formData) {
}
```
> **Good to know:** `updateTag` can only be called from a Server Action; calling it elsewhere throws. In Route Handlers or webhooks, use `revalidateTag` instead.
> **Good to know:** `updateTag` can only be called from a Server Action; calling it elsewhere throws. In Route Handlers or webhooks, use `revalidateTag` instead with a cache profile.
Pass `'max'` as the second argument to `revalidateTag` to expire the tag with stale-while-revalidate semantics:
```tsx filename="app/api/webhook/route.ts" switcher
// Before
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('posts')
return Response.json({ ok: true })
}
```
```js filename="app/api/webhook/route.js" switcher
// Before
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('posts')
return Response.json({ ok: true })
}
```
```tsx filename="app/api/webhook/route.ts" switcher
// After - Pass a cache profile
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('posts', 'max')
return Response.json({ ok: true })
}
```
```js filename="app/api/webhook/route.js" switcher
// After - Pass a cache profile
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('posts', 'max')
return Response.json({ ok: true })
}
```
## `unstable_noStore`
......@@ -578,7 +628,7 @@ The [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hoo
## `cookies`, `headers`, and `searchParams`
**Wrap runtime data access in `<Suspense>`.** Without Cache Components, reading [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), or [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) opts the whole route into dynamic rendering. With Cache Components, accessing them outside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary surfaces the [**blocking-route** insight](/docs/messages/blocking-prerender-dynamic). Move the access into a component wrapped in `<Suspense>` so the rest of the page prerenders as a static shell and the dynamic part streams in at request time.
**Wrap runtime data access in `<Suspense>`.** Without Cache Components, reading [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), or [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) opts the whole route into dynamic rendering. With Cache Components, accessing them outside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary surfaces the [**blocking-prerender-runtime** insight](/docs/messages/blocking-prerender-runtime). Move the access into a component wrapped in `<Suspense>` so the rest of the page prerenders as a static shell and the dynamic part streams in at request time.
```tsx filename="app/page.tsx" switcher
import { cookies } from 'next/headers'
......
......@@ -66,7 +66,7 @@ Learn more: [Streaming with Suspense](/docs/app/guides/streaming).
### Trade-off
The component shows the fallback during SSR and the first paint. For above-the-fold UI this can be visible.
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 the page doesn't visibly jump when the component hydrates. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -174,14 +174,9 @@ The user sees the placeholder briefly before the real value. For interactions th
- Only [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) ships to the browser. Node-only APIs (`crypto.randomBytes`, `crypto.generateKeyPairSync`) are not available on the client. If you're seeing this error for one of those, the call lives on the server: see [Crypto APIs during prerendering](/docs/messages/blocking-prerender-crypto).
- When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves.
## Don't want this validation?
## Why `instant = false` doesn't clear 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`](/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`](/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](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -73,7 +73,20 @@ export async function CsrfToken() {
}
```
Learn more: [`connection`](/docs/app/api-reference/functions/connection), [Streaming patterns and boundary placement](/docs/app/guides/streaming).
#### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws.
```jsx filename="app/dashboard/csrf-token.js"
import { io } from 'next/cache'
export async function CsrfToken() {
await io()
return <input type="hidden" name="csrf" value={crypto.randomUUID()} />
}
```
Learn more: [`connection`](/docs/app/api-reference/functions/connection), [`io`](/docs/app/api-reference/functions/io), [Streaming patterns and boundary placement](/docs/app/guides/streaming).
#### Switch to an async crypto API
......@@ -104,7 +117,7 @@ Learn more: [Node `crypto` API](https://nodejs.org/docs/latest/api/crypto.html).
### 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.
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 the page doesn't visibly jump when the content arrives. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -209,14 +222,9 @@ The first paint shows the SSR fallback (often `null`), and the value appears onl
- A Client Component that calls a crypto API inline during render still trips this error during SSR. See the dedicated [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client) page for the [`<Suspense>`](https://react.dev/reference/react/Suspense) and effect-based recipes.
- The browser only ships [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto). Node-only APIs (`crypto.randomBytes`, `crypto.generateKeyPairSync`) are not available on the client.
## Don't want this validation?
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`](/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`](/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`.
## Why `instant = false` doesn't clear this error
See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -78,7 +78,7 @@ Learn more: [Streaming with Suspense](/docs/app/guides/streaming).
### 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 to minimize visual jump.
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 to minimize visual jump. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -217,14 +217,9 @@ export default async function Layout({ children }) {
Learn more: [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time).
## Don't want this validation?
## Why `instant = false` doesn't clear 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`](/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`](/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](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -83,11 +83,24 @@ export async function UpdatedAt() {
}
```
Learn more: [Streaming patterns and boundary placement](/docs/app/guides/streaming).
#### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws.
```jsx filename="app/dashboard/updated-at.js"
import { io } from 'next/cache'
export async function UpdatedAt() {
await io()
return <small>Updated at {new Date().toLocaleString()}</small>
}
```
Learn more: [`io`](/docs/app/api-reference/functions/io), [Streaming patterns and boundary placement](/docs/app/guides/streaming).
### 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.
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 the page to visibly jump when the content arrives. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -266,14 +279,9 @@ Learn more: [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/A
- Don't pass a [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) value into the rendered output or into a cached function. The high-resolution timestamp is non-deterministic and shouldn't influence what's prerendered.
- For absolute time in an observability tool, use `performance.timeOrigin + performance.now()` to get a wall-clock timestamp without tripping this error.
## Don't want this validation?
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`](/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`](/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`.
## Why `instant = false` doesn't clear this error
See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -247,6 +247,7 @@ A useful rule: **push the boundary as low as possible** while keeping the fallba
- 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()`](/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}`.
- 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](/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
......
......@@ -67,7 +67,7 @@ Learn more: [Streaming with Suspense](/docs/app/guides/streaming).
### 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`](/docs/app/api-reference/file-conventions/loading) for full-segment fallback or pick a fallback that matches the final layout to minimize visual jump.
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 to minimize visual jump. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -167,14 +167,9 @@ The user sees the placeholder briefly before the real value. For interactions th
- If the value needs to be hydration-stable (the SSR HTML and the hydrated render must match exactly), use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead.
- When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves.
## Don't want this validation?
## Why `instant = false` doesn't clear 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`](/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`](/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](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -75,11 +75,25 @@ export async function RequestTrace() {
}
```
Learn more: [`connection`](/docs/app/api-reference/functions/connection), [Streaming patterns and boundary placement](/docs/app/guides/streaming).
#### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws.
```jsx filename="app/dashboard/request-trace.js"
import { io } from 'next/cache'
export async function RequestTrace() {
await io()
const traceId = Math.random().toString(16).slice(2)
return <small>trace: {traceId}</small>
}
```
Learn more: [`connection`](/docs/app/api-reference/functions/connection), [`io`](/docs/app/api-reference/functions/io), [Streaming patterns and boundary placement](/docs/app/guides/streaming).
### 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 the page doesn't visibly jump when the value arrives.
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 the page doesn't visibly jump when the value arrives. See [CLS-safe skeleton fallback guidance](/docs/app/guides/streaming#cls-cumulative-layout-shift).
### Gotchas
......@@ -187,14 +201,9 @@ The first paint shows the SSR fallback or initial state, and the random value ap
- A Client Component that produces a random value inline during render still trips this error during SSR. See the dedicated [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client) page for the [`<Suspense>`](https://react.dev/reference/react/Suspense) and effect-based recipes.
## Don't want this validation?
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`](/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`](/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`.
## Why `instant = false` doesn't clear this error
See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
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.
## Useful links
......
......@@ -170,6 +170,7 @@ A useful rule: **push the boundary as low as possible** while keeping the fallba
- 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()`](/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.
- 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
......
......@@ -23,7 +23,7 @@ Confirm each item before starting milestone A. The skill won't apply cleanly if
- `npx @next/codemod@latest upgrade latest` to apply the version-to-version codemods.
- Read the relevant [version upgrade guide](https://nextjs.org/docs/app/guides/upgrading) (e.g. [Version 16](https://nextjs.org/docs/app/guides/upgrading/version-16)) for what the codemod doesn't cover.
- **No incompatible config keys.** `cacheComponents: true` errors on any page that still exports `dynamic`. Other legacy route segment configs (`revalidate`, `fetchCache`) and the renamed `experimental.dynamicIO` / `experimental.useCache` should also be migrated. Resolve them via the [migration guide's "Enable Cache Components" section](https://nextjs.org/docs/app/guides/migrating-to-cache-components#enable-cache-components) before starting.
- **No incompatible config keys.** `cacheComponents: true` errors on any file that still exports `dynamic`, `revalidate`, or `fetchCache`. That covers pages and layouts, route handlers (`route.ts`), and metadata routes (`opengraph-image`, `icon`, `apple-icon`, `sitemap`, `manifest`, `robots`). The renamed `experimental.dynamicIO` / `experimental.useCache` should also be migrated. Resolve them via the [migration guide's "Enable Cache Components" section](https://nextjs.org/docs/app/guides/migrating-to-cache-components#enable-cache-components) before starting.
### notes
......@@ -85,7 +85,7 @@ Ask the user; don't assume. **In a non-interactive run** (no way to prompt), def
npx @next/codemod@canary cache-components-instant-false ./app
```
If `@next/codemod@latest` reports `Invalid transform choice`, try `@canary` — new transforms land there first.
If `@next/codemod@latest` reports `Invalid transform choice`, try `@canary` — new transforms land there first. The codemod refuses to run on a dirty working tree; commit or stash unrelated work first, or pass `--force` to override (the codemod's own edits then land alongside your WIP).
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 milestone B.
......
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