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

docs: clarify /_not-found failures and <html> attribute reads under Cache Components (#95163)

## Summary

When the root layout reads request data (`cookies()`, `headers()`) under
Cache Components, the validation error often surfaces on `/_not-found` —
a real prerendered route that inherits the root layout, even though the
user has no `not-found.tsx` file. This is consistently confusing
(#67532), so:

- `errors/blocking-prerender-runtime.mdx` and
`errors/blocking-prerender-dynamic.mdx`: added a gotcha bullet pointing
the fix at the root layout when the failing route is `/_not-found`.
- `docs/01-app/02-guides/migrating-to-cache-components.mdx`: added a
`Good to know` callout in the `cookies, headers, and searchParams`
section linking to the existing [Themes
recipe](/docs/app/guides/preventing-flash-before-hydration#themes) for
the `<html data-theme>` case, since attributes on the root element can
not be wrapped in `<Suspense>`.

## Verification

- `npx alex` clean on all three files.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarJoseph Chamochumbi <joseph.chamochumbi@vercel.com>
Co-authored-by: 's avatarCopilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
parent 1d09001f
...@@ -739,6 +739,8 @@ async function Results({ searchParams }) { ...@@ -739,6 +739,8 @@ async function Results({ searchParams }) {
} }
``` ```
> **Good to know**: When a cookie or header value drives an attribute on the `<html>` element in the root layout (`lang`, `dir`, `data-theme`, etc.), reading it on the server makes the whole subtree request-bound, so there's no child to wrap in `<Suspense>`. An inline `<script>` in `<head>` that sets the attribute before paint keeps the shell static; see [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration) for the pattern.
## Route Handlers (`GET`) ## Route Handlers (`GET`)
**Replace `dynamic = 'force-static'` with `use cache`.** **Replace `dynamic = 'force-static'` with `use cache`.**
......
...@@ -246,11 +246,7 @@ export default async function Page() { ...@@ -246,11 +246,7 @@ export default async function Page() {
Your page may be server-rendered with a default theme (e.g. light), but the user has a saved preference in `localStorage`. The same inline script technique works: read the value and set a `data-theme` attribute on `<html>` before the browser paints. Your page may be server-rendered with a default theme (e.g. light), but the user has a saved preference in `localStorage`. The same inline script technique works: read the value and set a `data-theme` attribute on `<html>` before the browser paints.
```tsx filename="app/layout.tsx" switcher ```tsx filename="app/layout.tsx" switcher
export default function RootLayout({ export default function RootLayout({ children }: LayoutProps<'/'>) {
children,
}: {
children: React.ReactNode
}) {
return ( return (
<html lang="en" data-theme="light" suppressHydrationWarning> <html lang="en" data-theme="light" suppressHydrationWarning>
<head> <head>
...@@ -297,6 +293,52 @@ export default function RootLayout({ children }) { ...@@ -297,6 +293,52 @@ export default function RootLayout({ children }) {
The script runs in `<head>`, so the correct theme is applied before any content is painted. The `try/catch` handles cases where `localStorage` is unavailable. The script runs in `<head>`, so the correct theme is applied before any content is painted. The `try/catch` handles cases where `localStorage` is unavailable.
### Storing the theme in a cookie
Unlike `localStorage`, a cookie is sent with every request, so the server _can_ read it with [`cookies()`](/docs/app/api-reference/functions/cookies). But reading it in the root layout opts the entire app out of static prerendering (and under [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), forces blocking every segment under the layout). To keep the page statically prerendered with a generic default and still avoid the flash, read the cookie in the inline script instead:
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en" data-theme="light" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `(function(){try{var m=document.cookie.match(/(?:^|; )theme=([^;]*)/);if(m)document.documentElement.setAttribute("data-theme",decodeURIComponent(m[1]))}catch(e){}})()`,
}}
/>
</head>
<body>{children}</body>
</html>
)
}
```
```jsx filename="app/layout.js" switcher
export default function RootLayout({ children }) {
return (
<html lang="en" data-theme="light" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `(function(){try{var m=document.cookie.match(/(?:^|; )theme=([^;]*)/);if(m)document.documentElement.setAttribute("data-theme",decodeURIComponent(m[1]))}catch(e){}})()`,
}}
/>
</head>
<body>{children}</body>
</html>
)
}
```
To switch themes, set the attribute on `<html>` and persist the choice to the cookie:
```js
const theme = 'dark'
document.documentElement.setAttribute('data-theme', theme)
document.cookie = `theme=${encodeURIComponent(theme)}; path=/; max-age=31536000; SameSite=Lax`
```
## Syncing with React state ## Syncing with React state
When a Client Component manages interactive state (like which accordion section is open), React's initial state must match the DOM that the inline script set. Use a **lazy state initializer** that reads from the same source as the script. When a Client Component manages interactive state (like which accordion section is open), React's initial state must match the DOM that the inline script set. Use a **lazy state initializer** that reads from the same source as the script.
......
...@@ -9,7 +9,7 @@ Request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [ ...@@ -9,7 +9,7 @@ Request-bound reads ([`cookies()`](/docs/app/api-reference/functions/cookies), [
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). 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).
> **Good to know**: In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component. Run `next build --debug-prerender` to get the full list of blocking routes with stack traces. When iterating on specific routes, use `next build --debug-build-paths /dashboard /settings` to rebuild only those pages. > **Good to know**: 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. The default `next build` output is more abbreviated: the stack often shows only anonymous HTML elements without user file paths. Run `next build --debug-prerender` to get the full list of blocking routes with user-frame stack traces, and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Ways to fix this ## Ways to fix this
...@@ -246,6 +246,7 @@ A useful rule: **push the boundary as low as possible** while keeping the fallba ...@@ -246,6 +246,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. - 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}`. - 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`.
- 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. - 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. - 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.
......
...@@ -9,7 +9,7 @@ Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web ...@@ -9,7 +9,7 @@ Uncached data accesses ([`fetch()`](https://developer.mozilla.org/en-US/docs/Web
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). 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).
> **Good to know**: In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component. Run `next build --debug-prerender` to get the full list of blocking routes with stack traces. When iterating on specific routes, use `next build --debug-build-paths /dashboard /settings` to rebuild only those pages. > **Good to know**: 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. The default `next build` output is more abbreviated: the stack often shows only anonymous HTML elements without user file paths. Run `next build --debug-prerender` to get the full list of blocking routes with user-frame stack traces, and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes.
## Ways to fix this ## Ways to fix this
...@@ -167,6 +167,7 @@ A useful rule: **push the boundary as low as possible** while keeping the fallba ...@@ -167,6 +167,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. - 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 [`headers()`](/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`.
- 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. - 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 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.
......
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