Unverified Commit 41215d77 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

Add Instant Insights for prefetch() and navigation() (#97801)

Closes NAR-929

## Summary

- add render stages in validation so Instant Navigation validation can
distinguish `prefetch()` from URL data
- report `prefetch()` and `navigation()` consistently across route
bodies, metadata, and viewport
- show non-blocking findings as amber Instant Insights while keeping
prerender failures as red errors
- document navigation stages and cross-link the stable `prefetch()` and
`navigation()` APIs from their references and the Optimizing Prefetching
guide

The DevTools cards, terminal guidance, and error pages use the same
recommended fixes. Metadata guidance lets developers remove the stage
API or confirm the delay from the page. Viewport guidance lets
developers remove the API or disable validation with `instant = false`.

## Implementation notes

Adds two new sub-stages that are only used for dynamic hole
discrimination:
- `PrefetchStatic_prefetch` (subset of `PrefetchStatic`)
- `PrefetchRuntime_prefetch` (subset of `PrefetchRuntime`)
The stages run before the semantic `PrefetchStatic` and
`PrefetchRuntime` stages respectively.
We resolve `prefetch()` resolves there in renders that produce
validation error messages.
the validation sequences map the stages to a prefetch() hole
kind and produce a specialized error message, distinct from URL data.

In non-validation renders, we skip the sub-stages and advance to
`PrefetchStatic`/`PrefetchRuntime` directly,
which resolves `prefetch()` in the same task as other URL data.

We also reorganize `RENDER_STAGES_BY_DATA_KIND`. We have
`staticUrlData['static' | 'runtime']` to separate data that is
_semantically_ statically prerenderable (but may be deferred to a
runtime stage for implementation reasons) from `runtimeUrlData`, which
is never statically prerenderable.

## Preview scenarios

- [`navigation()` outside of
Suspense](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/119-navigation-body)
- [`navigation()` in
`generateMetadata()`](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/120-navigation-in-metadata)
- [`navigation()` in
`generateViewport()`](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/121-navigation-in-viewport)
- [`prefetch()` outside of
Suspense](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/122-prefetch-body)
- [`prefetch()` in
`generateMetadata()`](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/123-prefetch-in-metadata)
- [`prefetch()` in
`generateViewport()`](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/124-prefetch-in-viewport)

## Verification

- 145 focused DevTools unit tests
- 108 Partial Prefetching Instant Validation tests, including 64
snapshots
- 32 Instant Navigation DevTools tests
- `pnpm --filter=next types`
- `pnpm --filter=next build`
- Documentation link validation passed

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
Co-authored-by: 's avatarClaude Fable 5.1 <noreply@anthropic.com>
parent 4103f837
...@@ -167,11 +167,9 @@ async function Stories() { ...@@ -167,11 +167,9 @@ async function Stories() {
- The function has no effect on the initial load of a page. - The function has no effect on the initial load of a page.
- Reading `cookies()` or `headers()` below `navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either. - Reading `cookies()` or `headers()` below `navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either.
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell. - A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws. - Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
{/* TODO: link the validation insight error page from the bullet above once it merges. */}
## Reference ## Reference
### Type ### Type
......
...@@ -147,12 +147,10 @@ When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and ...@@ -147,12 +147,10 @@ When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and
## Good to know ## Good to know
- The function has no effect on the initial load of a page. - The function has no effect on the initial load of a page.
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell. - A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws. - Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
- In a `page` or `layout` that sets the [`prefetch` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/prefetch), import the function under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`, since both are named `prefetch`. - In a `page` or `layout` that sets the [`prefetch` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/prefetch), import the function under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`, since both are named `prefetch`.
{/* TODO: link the validation insight error page from the bullet above once it merges. */}
## Reference ## Reference
### Type ### Type
......
---
title: Next.js encountered `prefetch()` or `navigation()` in `generateMetadata()`
kind: insight
---
<div
style={{
padding: '1.25rem 1.5rem',
border: '1px solid var(--ds-gray-400)',
borderRadius: '12px',
background: 'var(--ds-background-200)',
margin: '1.5rem 0 2rem',
fontSize: '0.95rem',
lineHeight: '1.6',
}}
>
This insight is part of the [Instant
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
instant navigations](/docs/app/guides/instant-navigation) guide for an
overview of what instant navigations are and how Next.js validates them, then
come back here for the specific fix.
</div>
During prerendering or a client-side navigation, [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata) called [`prefetch()`](/docs/app/api-reference/functions/prefetch) or [`navigation()`](/docs/app/api-reference/functions/navigation). These [navigation stage APIs](/docs/app/glossary#navigation-stages) delay the metadata work until a per-link prefetch or navigation, depending on which API you use.
Metadata can already stream, so delaying it may be unintentional. Remove the API call if you do not need the delay. Otherwise, confirm that the metadata delay is intentional.
For the same insight in the page body or viewport code, see [`prefetch()` or `navigation()` outside of Suspense](/docs/messages/instant-navigation-stage) or [`prefetch()` or `navigation()` in `generateViewport()`](/docs/messages/instant-navigation-stage-viewport).
## Ways to fix this
<FixCardGrid>
<FixCard
group="remove"
title="Remove the API call"
href="#remove-the-api-call"
snippets={[
{ text: 'async function generateMetadata() {' },
{ text: '- await navigation()', highlight: true },
{ text: '}' },
]}
/>
<FixCard
group="mark"
title="Confirm the metadata delay"
href="#confirm-the-metadata-delay"
snippets={[
{ text: '// page.tsx or layout.tsx' },
{ text: 'await navigation()', highlight: true },
]}
/>
</FixCardGrid>
## Remove the API call
Choose this fix when you do not need to control when the metadata is included. Remove `prefetch()` or `navigation()` from [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata). Keep `generateMetadata()` and its existing caching.
### Patterns
#### Remove the API call
Remove the call to `prefetch()` or `navigation()`.
```jsx filename="app/dashboard/page.js"
import { getMetadata } from './data'
export async function generateMetadata() {
return getMetadata()
}
export default function Page() {
return <main>Dashboard</main>
}
```
Learn more: [`generateMetadata()`](/docs/app/api-reference/functions/generate-metadata).
### Trade-off
Removing the API can increase the metadata work performed during prerendering and prefetching.
### Gotchas
- You do not need to replace `generateMetadata()` with a static [`metadata`](/docs/app/api-reference/functions/generate-metadata#the-metadata-object) export. Use a static export only when the values are fixed for the route segment.
## Confirm the metadata delay
Choose this fix when the page can render earlier but the metadata should remain at the selected navigation stage. Create a component that calls the same API as `generateMetadata()` and returns `null`. Render it inside [`<Suspense>`](https://react.dev/reference/react/Suspense).
This insight appears because metadata is the only part of the route delayed to that stage. Calling the same API from the page confirms that the timing is intentional.
### Patterns
#### Add a navigation stage marker
Create the marker and render it inside [`<Suspense>`](https://react.dev/reference/react/Suspense). The existing page content remains available at its current stages.
This example uses [`navigation()`](/docs/app/api-reference/functions/navigation). If `generateMetadata()` calls [`prefetch()`](/docs/app/api-reference/functions/prefetch), call `prefetch()` in the marker instead.
```jsx filename="app/dashboard/page.js"
import { Suspense } from 'react'
import { navigation } from 'next/cache'
import { getMetadata } from './data'
export async function generateMetadata() {
await navigation()
return getMetadata()
}
async function NavigationStageMarker() {
await navigation()
return null
}
export default function Page() {
return (
<>
<main>Dashboard</main>
<Suspense>
<NavigationStageMarker />
</Suspense>
</>
)
}
```
Learn more: [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation).
### Trade-off
The metadata remains cacheable, but is unavailable until the selected navigation stage.
### Gotchas
- The marker must call the same navigation stage API as `generateMetadata()`.
- The marker must render inside [`<Suspense>`](https://react.dev/reference/react/Suspense). Without the boundary, the page surfaces [navigation stage API outside of Suspense](/docs/messages/instant-navigation-stage).
- If the page already calls the same navigation stage API inside a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary, you won't see this insight. The page already includes work at the same stage.
## Verifying the fix
After applying a fix, navigate to the route and confirm the insight no longer appears. The page should paint meaningful UI immediately. Keep `<Suspense>` fallbacks scoped to the regions that stream in. A boundary around the whole page can pass validation with an empty shell, which defeats instant navigation.
In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay identifies the failing component with a file path and line number. The default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is shorter. Run `next build --debug-prerender` for full user-frame stack traces or `next build --debug-build-paths /dashboard /settings` to inspect specific routes.
## 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 surfaces this insight.
- **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.
## Related Insights
See [Instant Navigation validation errors](/docs/messages/instant-navigation-validation) for the complete reference.
---
title: Next.js encountered `prefetch()` or `navigation()` in `generateViewport()`
kind: insight
---
<div
style={{
padding: '1.25rem 1.5rem',
border: '1px solid var(--ds-gray-400)',
borderRadius: '12px',
background: 'var(--ds-background-200)',
margin: '1.5rem 0 2rem',
fontSize: '0.95rem',
lineHeight: '1.6',
}}
>
This insight is part of the [Instant
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
instant navigations](/docs/app/guides/instant-navigation) guide for an
overview of what instant navigations are and how Next.js validates them, then
come back here for the specific fix.
</div>
During prerendering or a client-side navigation, [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport) called [`prefetch()`](/docs/app/api-reference/functions/prefetch) or [`navigation()`](/docs/app/api-reference/functions/navigation). `prefetch()` delays the viewport until a per-link prefetch or navigation. `navigation()` delays it until navigation.
Next.js needs the viewport before it can complete the route's [App Shell](/docs/app/glossary#app-shell). Holding the viewport until a later stage prevents Next.js from creating the App Shell and can make navigation slower. If the later timing is not intentional, remove the API call. If it is intentional, you can leave the behavior unchanged. To stop reporting the insight, disable validation for the segment.
For the same insight in the page body or metadata code, see [`prefetch()` or `navigation()` outside of Suspense](/docs/messages/instant-navigation-stage) or [`prefetch()` or `navigation()` in `generateMetadata()`](/docs/messages/instant-navigation-stage-metadata).
## Ways to fix this
<FixCardGrid>
<FixCard
group="remove"
title="Remove the API call"
href="#remove-the-api-call"
snippets={[
{ text: 'async function generateViewport() {' },
{ text: '- await navigation()', highlight: true },
{ text: '}' },
]}
/>
<FixCard
group="ignore"
title="Disable validation on this route"
href="#disable-validation-on-this-route"
snippets={[
{ text: '// page.tsx or layout.tsx' },
{ text: 'export const instant = false', highlight: true },
]}
/>
</FixCardGrid>
## Remove the API call
Choose this fix when you do not need to control when the viewport is included. Remove `prefetch()` or `navigation()` from [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport). Keep `generateViewport()` and its existing caching.
### Patterns
#### Remove the API call
Remove the call to `prefetch()` or `navigation()`.
```jsx filename="app/dashboard/layout.js"
import { getViewport } from './data'
export async function generateViewport() {
return getViewport()
}
export default function DashboardLayout({ children }) {
return children
}
```
Learn more: [`generateViewport()`](/docs/app/api-reference/functions/generate-viewport).
### Trade-off
Removing the API can increase the viewport work performed during prerendering and prefetching.
### Gotchas
- You do not need to replace `generateViewport()` with a static [`viewport`](/docs/app/api-reference/functions/generate-viewport#the-viewport-object) export. Use a static export only when the values are fixed for the route segment.
## Disable validation on this route
Choose this fix when the later viewport timing is intentional and you do not want Next.js to report the insight. Add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout that exports `generateViewport()`. This disables instant-navigation validation for the segment. It does not change when the viewport becomes available.
### Patterns
#### Disable validation for the segment
```jsx filename="app/dashboard/layout.js"
export const instant = false
```
Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
### Trade-off
The viewport remains unavailable until the selected navigation stage, but Next.js no longer reports the delay for this segment.
### Gotchas
- Child segments are still validated during client navigations.
- The export does not change when the viewport becomes available or disable prerendering.
## Verifying the fix
After applying a fix, navigate to the route and confirm the insight no longer appears. The page should paint meaningful UI immediately.
In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay identifies the failing component with a file path and line number. The default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is shorter. Run `next build --debug-prerender` for full user-frame stack traces or `next build --debug-build-paths /dashboard /settings` to inspect specific routes.
## 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 surfaces this insight.
- **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.
## Related Insights
See [Instant Navigation validation errors](/docs/messages/instant-navigation-validation) for the complete reference.
---
title: Next.js encountered `prefetch()` or `navigation()` outside of Suspense
kind: insight
---
<div
style={{
padding: '1.25rem 1.5rem',
border: '1px solid var(--ds-gray-400)',
borderRadius: '12px',
background: 'var(--ds-background-200)',
margin: '1.5rem 0 2rem',
fontSize: '0.95rem',
lineHeight: '1.6',
}}
>
This insight is part of the [Instant
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
instant navigations](/docs/app/guides/instant-navigation) guide for an
overview of what instant navigations are and how Next.js validates them, then
come back here for the specific fix.
</div>
During prerendering or a client-side navigation, a Server Component called [`prefetch()`](/docs/app/api-reference/functions/prefetch) or [`navigation()`](/docs/app/api-reference/functions/navigation) outside of [`<Suspense>`](https://react.dev/reference/react/Suspense). These [navigation stage APIs](/docs/app/glossary#navigation-stages) need a fallback when they exclude a subtree from a prefetch.
During runtime rendering, `prefetch()` excludes subsequent content from the [App Shell](/docs/app/glossary#app-shell) but includes it in `<Link prefetch={true}>` prefetches and navigations. `navigation()` excludes the content from both the App Shell and per-link prefetches, then renders it during navigation. Neither API affects initial loads or [static prerenders](/docs/app/glossary#prerendering), and subsequent content remains cacheable.
For the same insight in metadata or viewport code, see [`prefetch()` or `navigation()` in `generateMetadata()`](/docs/messages/instant-navigation-stage-metadata) or [`prefetch()` or `navigation()` in `generateViewport()`](/docs/messages/instant-navigation-stage-viewport).
## Ways to fix this
<FixCardGrid>
<FixCard
group="stream"
title="Wrap in or move into Suspense"
href="#wrap-in-or-move-into-suspense"
snippets={[
{ text: '<Suspense fallback={…}>', highlight: true },
{ text: ' <DataChild />' },
{ text: '</Suspense>', highlight: true },
]}
/>
<FixCard
group="block"
title="Allow blocking route"
href="#allow-blocking-route"
snippets={[
{ text: '// page.tsx or layout.tsx' },
{ text: 'export const instant = false', highlight: true },
]}
/>
</FixCardGrid>
## Wrap in or move into Suspense
Choose this fix when the route has meaningful UI before the deferred content. Place [`<Suspense>`](https://react.dev/reference/react/Suspense) around the smallest region that calls the navigation stage API.
### Patterns
#### Include content in a per-link prefetch
Use `prefetch()` when the region should be absent from the App Shell but available to links that use `prefetch={true}`.
```jsx filename="app/products/page.js"
import { Suspense } from 'react'
import { prefetch } from 'next/cache'
async function Recommendations() {
await prefetch()
return <ProductGrid products={await getRecommendations()} />
}
export default function Page() {
return (
<main>
<h1>Products</h1>
<Suspense fallback={<ProductGridSkeleton />}>
<Recommendations />
</Suspense>
</main>
)
}
```
Learn more: [`prefetch()`](/docs/app/api-reference/functions/prefetch).
#### Defer content until navigation
Use `navigation()` when the region should be absent from prefetches and rendered only after navigation begins.
```jsx filename="app/dashboard/page.js"
import { Suspense } from 'react'
import { navigation } from 'next/cache'
async function RecentActivity() {
await navigation()
return <ActivityList activity={await getRecentActivity()} />
}
export default function Page() {
return (
<Dashboard>
<h1>Overview</h1>
<Suspense fallback={<ActivitySkeleton />}>
<RecentActivity />
</Suspense>
</Dashboard>
)
}
```
Learn more: [`navigation()`](/docs/app/api-reference/functions/navigation) and [Streaming](/docs/app/guides/streaming).
### Trade-off
The earlier prefetch contains the fallback instead of the deferred content. A per-link prefetch adds speculative server work for content below `prefetch()`, while content below `navigation()` does not begin rendering until navigation.
### Gotchas
- The boundary must be above the component that awaits the navigation stage API. Adding a boundary inside that component does not catch the suspension.
- Navigation stage APIs cannot run inside a `use cache`, `use cache: private`, or [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) scope. Put the cache directive on a function called after the stage boundary.
- Static prerenders resolve both functions because the work runs once and is shared. Next.js still requires a boundary so the route remains valid if it later needs a runtime App Shell.
## Allow blocking route
Choose this fix when the route has no meaningful UI before the deferred content. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` exempts the segment from instant-navigation validation.
### Patterns
#### Opt the page out
Add the export to the page that calls the navigation stage API. Only that route is allowed to block.
```jsx filename="app/dashboard/page.js"
import { navigation } from 'next/cache'
export const instant = false
export default async function Page() {
await navigation()
return <Dashboard />
}
```
Learn more: [Ensuring instant navigations](/docs/app/guides/instant-navigation).
#### Opt the layout out
Add the export to a layout when the shared segment has no useful earlier state.
```jsx filename="app/dashboard/layout.js"
export const instant = false
export default function DashboardLayout({ children }) {
return <DashboardShell>{children}</DashboardShell>
}
```
Learn more: [Route segment `instant` config](/docs/app/api-reference/file-conventions/route-segment-config/instant).
Use either pattern when:
- The segment intentionally has no meaningful UI before the point selected by the navigation stage API.
- You're migrating the route incrementally and need to preserve its current blocking behavior.
Don't use this to dismiss the insight. Choose [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) when a useful fallback exists.
### Trade-off
Navigations to this route are not instant. The browser waits for the full server render before receiving HTML. Use this only when the route requires that delay.
### Gotchas
- Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` opts out only the segment that exports it. Descendant segments remain validated by their own config or the global default.
- 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
After applying a fix, navigate to the route and confirm the insight no longer appears. The page should paint meaningful UI immediately. Keep `<Suspense>` fallbacks scoped to the regions that stream in. A boundary around the whole page can pass validation with an empty shell, which defeats instant navigation.
In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay identifies the failing component with a file path and line number. The default [`next build`](/docs/app/api-reference/cli/next#next-build-options) output is shorter. Run `next build --debug-prerender` for full user-frame stack traces or `next build --debug-build-paths /dashboard /settings` to inspect specific routes.
## 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 surfaces this insight.
- **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.
## Related Insights
See [Instant Navigation validation errors](/docs/messages/instant-navigation-validation) for the complete reference.
...@@ -32,8 +32,11 @@ If the error only appears during `next build`, follow [Debug prerender errors](/ ...@@ -32,8 +32,11 @@ If the error only appears during `next build`, follow [Debug prerender errors](/
## Non-blocking insights ## Non-blocking insights
These insights identify content that is deferred to a later navigation stage without blocking navigation. These insights identify work that is deferred to a later navigation stage, or changes what a prefetch contains, without blocking navigation.
- [`prefetch()` or `navigation()` outside of Suspense](/docs/messages/instant-navigation-stage)
- [`prefetch()` or `navigation()` in `generateMetadata()`](/docs/messages/instant-navigation-stage-metadata)
- [`prefetch()` or `navigation()` in `generateViewport()`](/docs/messages/instant-navigation-stage-viewport)
- [Dynamic data during prefetching](/docs/messages/instant-link-prefetch-partial) - [Dynamic data during prefetching](/docs/messages/instant-link-prefetch-partial)
- [URL data outside of Suspense](/docs/messages/instant-shell-url-data) - [URL data outside of Suspense](/docs/messages/instant-shell-url-data)
- [Unrendered segment](/docs/messages/instant-unrendered-segment) - [Unrendered segment](/docs/messages/instant-unrendered-segment)
......
...@@ -26,7 +26,7 @@ During a [client-side navigation](/docs/app/glossary#client-side-navigation), a ...@@ -26,7 +26,7 @@ During a [client-side navigation](/docs/app/glossary#client-side-navigation), a
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 `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](/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). Next.js validates the route on both initial loads and client navigations, but this insight applies to the App Shell used for client-side navigation. On initial load, the same read surfaces as [runtime data during prerendering](/docs/messages/blocking-prerender-runtime) while Next.js validates the route's [static shell](/docs/app/glossary#static-shell). 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
...@@ -129,7 +129,7 @@ The shared parts of the route are prefetched, and the URL-dependent region strea ...@@ -129,7 +129,7 @@ The shared parts of the route are prefetched, and the URL-dependent region strea
## 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`](/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 needs URL data high in the tree and cannot provide a shared App Shell. Navigations to the route will not be instant. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` allows the segment to block, so it renders per navigation instead of reusing a shared prefetch.
### Patterns ### Patterns
......
...@@ -38,6 +38,8 @@ export async function GET() { ...@@ -38,6 +38,8 @@ export async function GET() {
Request-time APIs like `headers()`, `cookies()`, `connection()`, and `draftMode()` are not available inside `generateStaticParams` because it runs at build time to determine which pages to statically generate. There is no HTTP request in this context. Request-time APIs like `headers()`, `cookies()`, `connection()`, and `draftMode()` are not available inside `generateStaticParams` because it runs at build time to determine which pages to statically generate. There is no HTTP request in this context.
Likewise, `prefetch()` and `navigation()` are not available there because no prefetch or navigation takes place while Next.js generates route parameters.
Note: Root param getters (`import { lang } from 'next/root-params'`) _are_ supported inside `generateStaticParams` for nested segments, as the parent params are known at that point. Note: Root param getters (`import { lang } from 'next/root-params'`) _are_ supported inside `generateStaticParams` for nested segments, as the parent params are known at that point.
## Useful Links ## Useful Links
...@@ -45,5 +47,7 @@ Note: Root param getters (`import { lang } from 'next/root-params'`) _are_ suppo ...@@ -45,5 +47,7 @@ Note: Root param getters (`import { lang } from 'next/root-params'`) _are_ suppo
- [`headers()` function](/docs/app/api-reference/functions/headers) - [`headers()` function](/docs/app/api-reference/functions/headers)
- [`cookies()` function](/docs/app/api-reference/functions/cookies) - [`cookies()` function](/docs/app/api-reference/functions/cookies)
- [`draftMode()` function](/docs/app/api-reference/functions/draft-mode) - [`draftMode()` function](/docs/app/api-reference/functions/draft-mode)
- [`prefetch()` function](/docs/app/api-reference/functions/prefetch)
- [`navigation()` function](/docs/app/api-reference/functions/navigation)
- [`unstable_noStore()` function](/docs/app/api-reference/functions/unstable_noStore) - [`unstable_noStore()` function](/docs/app/api-reference/functions/unstable_noStore)
- [`unstable_cache()` function](/docs/app/api-reference/functions/unstable_cache) - [`unstable_cache()` function](/docs/app/api-reference/functions/unstable_cache)
...@@ -8,6 +8,8 @@ A cached function tried to access the incoming request. APIs such as `cookies()` ...@@ -8,6 +8,8 @@ A cached function tried to access the incoming request. APIs such as `cookies()`
A cached function can also stall if it awaits a promise stored outside the function, such as one kept in a module-scoped `Map` for deduplication. A cached function can also stall if it awaits a promise stored outside the function, such as one kept in a module-scoped `Map` for deduplication.
`prefetch()` and `navigation()` are also unavailable inside cached functions. Move the stage boundary outside the cached function, then call the cached function below it so only the deferred work is cached.
## Possible Ways to Fix It ## Possible Ways to Fix It
Read and resolve request data outside the cached function, then pass only the values you need as arguments. Call `connection()` and enable or disable draft mode outside the cached function as well. Read and resolve request data outside the cached function, then pass only the values you need as arguments. Call `connection()` and enable or disable draft mode outside the cached function as well.
...@@ -54,4 +56,6 @@ export default async function Page() { ...@@ -54,4 +56,6 @@ export default async function Page() {
- [`cookies()` function](/docs/app/api-reference/functions/cookies) - [`cookies()` function](/docs/app/api-reference/functions/cookies)
- [`connection()` function](/docs/app/api-reference/functions/connection) - [`connection()` function](/docs/app/api-reference/functions/connection)
- [`draftMode()` function](/docs/app/api-reference/functions/draft-mode) - [`draftMode()` function](/docs/app/api-reference/functions/draft-mode)
- [`prefetch()` function](/docs/app/api-reference/functions/prefetch)
- [`navigation()` function](/docs/app/api-reference/functions/navigation)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache) - [`use cache` directive](/docs/app/api-reference/directives/use-cache)
...@@ -4,14 +4,17 @@ import { ...@@ -4,14 +4,17 @@ import {
createRuntimeBodyErrorInNavigation, createRuntimeBodyErrorInNavigation,
createLinkBodyErrorInNavigation, createLinkBodyErrorInNavigation,
createNavigationBodyErrorInNavigation, createNavigationBodyErrorInNavigation,
createPrefetchBodyErrorInNavigation,
createDynamicBodyErrorInNavigation, createDynamicBodyErrorInNavigation,
createRuntimeMetadataError, createRuntimeMetadataError,
createLinkMetadataError, createLinkMetadataError,
createNavigationMetadataError, createNavigationMetadataError,
createPrefetchMetadataError,
createDynamicMetadataError, createDynamicMetadataError,
createRuntimeViewportError, createRuntimeViewportError,
createLinkViewportError, createLinkViewportError,
createNavigationViewportError, createNavigationViewportError,
createPrefetchViewportError,
createDynamicViewportError, createDynamicViewportError,
} from '../../../../server/app-render/blocking-route-messages' } from '../../../../server/app-render/blocking-route-messages'
import { createLinkPrefetchPartialError } from '../../../../shared/lib/instant-messages' import { createLinkPrefetchPartialError } from '../../../../shared/lib/instant-messages'
...@@ -44,6 +47,7 @@ describe('static route explanations', () => { ...@@ -44,6 +47,7 @@ describe('static route explanations', () => {
const GUIDANCE_VARIANTS = [ const GUIDANCE_VARIANTS = [
'runtime', 'runtime',
'link', 'link',
'prefetch',
'navigation', 'navigation',
'dynamic', 'dynamic',
] as const satisfies GuidanceVariant[] ] as const satisfies GuidanceVariant[]
...@@ -88,6 +92,12 @@ describe('instant-guidance-data card ordering', () => { ...@@ -88,6 +92,12 @@ describe('instant-guidance-data card ordering', () => {
'blocking-route', 'blocking-route',
'link', 'link',
], ],
[
'blocking-route prefetch in navigation',
createPrefetchBodyErrorInNavigation('/x').message,
'blocking-route',
'prefetch',
],
[ [
'blocking-route navigation in navigation', 'blocking-route navigation in navigation',
createNavigationBodyErrorInNavigation('/x').message, createNavigationBodyErrorInNavigation('/x').message,
...@@ -113,6 +123,12 @@ describe('instant-guidance-data card ordering', () => { ...@@ -113,6 +123,12 @@ describe('instant-guidance-data card ordering', () => {
'metadata', 'metadata',
'link', 'link',
], ],
[
'metadata prefetch',
createPrefetchMetadataError('/x').message,
'metadata',
'prefetch',
],
[ [
'metadata navigation', 'metadata navigation',
createNavigationMetadataError('/x').message, createNavigationMetadataError('/x').message,
...@@ -138,6 +154,12 @@ describe('instant-guidance-data card ordering', () => { ...@@ -138,6 +154,12 @@ describe('instant-guidance-data card ordering', () => {
'viewport', 'viewport',
'link', 'link',
], ],
[
'viewport prefetch',
createPrefetchViewportError('/x').message,
'viewport',
'prefetch',
],
[ [
'viewport navigation', 'viewport navigation',
createNavigationViewportError('/x').message, createNavigationViewportError('/x').message,
......
import { import {
FixCardAlignLeftIcon, FixCardAlignLeftIcon,
FixCardArrowUpIcon, FixCardArrowUpIcon,
FixCardCheckIcon,
FixCardDatabaseIcon, FixCardDatabaseIcon,
FixCardHistoryIcon, FixCardHistoryIcon,
FixCardLayoutIcon, FixCardLayoutIcon,
...@@ -61,6 +62,8 @@ function getCardIcon(icon: FixCardIcon) { ...@@ -61,6 +62,8 @@ function getCardIcon(icon: FixCardIcon) {
return <FixCardLayoutIcon /> return <FixCardLayoutIcon />
case 'arrow-up': case 'arrow-up':
return <FixCardArrowUpIcon /> return <FixCardArrowUpIcon />
case 'check':
return <FixCardCheckIcon />
case 'minus': case 'minus':
return <FixCardMinusIcon /> return <FixCardMinusIcon />
default: default:
......
...@@ -38,6 +38,8 @@ import { ...@@ -38,6 +38,8 @@ import {
import { import {
BLOCKING_ROUTE_IN_NAVIGATION_EXPLANATION, BLOCKING_ROUTE_IN_NAVIGATION_EXPLANATION,
BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION, BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION,
CACHE_STAGE_METADATA_EXPLANATION,
CACHE_STAGE_VIEWPORT_EXPLANATION,
} from '../components/instant/instant-guidance-data' } from '../components/instant/instant-guidance-data'
import { UnrenderedSegmentInfo } from '../components/instant/unrendered-segment-info' import { UnrenderedSegmentInfo } from '../components/instant/unrendered-segment-info'
import { CodeFrame } from '../components/code-frame/code-frame' import { CodeFrame } from '../components/code-frame/code-frame'
...@@ -105,10 +107,16 @@ export function getErrorTypeLabel( ...@@ -105,10 +107,16 @@ export function getErrorTypeLabel(
if (errorDetails.type === 'client-hook') { if (errorDetails.type === 'client-hook') {
return `Blocking Route` return `Blocking Route`
} }
if (errorDetails.type === 'dynamic-metadata') { if (
return `Blocking Route` errorDetails.type === 'dynamic-metadata' ||
} errorDetails.type === 'dynamic-viewport'
if (errorDetails.type === 'dynamic-viewport') { ) {
if (
errorDetails.variant === 'prefetch' ||
errorDetails.variant === 'navigation'
) {
return `Instant`
}
return `Blocking Route` return `Blocking Route`
} }
if (errorDetails.type === 'sync-io') { if (errorDetails.type === 'sync-io') {
...@@ -177,11 +185,13 @@ type ClientHookErrorDetails = { ...@@ -177,11 +185,13 @@ type ClientHookErrorDetails = {
type DynamicMetadataErrorDetails = { type DynamicMetadataErrorDetails = {
type: 'dynamic-metadata' type: 'dynamic-metadata'
variant: GuidanceVariant variant: GuidanceVariant
explanation?: string
} }
type DynamicViewportErrorDetails = { type DynamicViewportErrorDetails = {
type: 'dynamic-viewport' type: 'dynamic-viewport'
variant: GuidanceVariant variant: GuidanceVariant
explanation?: string
} }
type SyncIOErrorDetails = { type SyncIOErrorDetails = {
...@@ -377,6 +387,9 @@ export function getGuidanceVariant(message: string): GuidanceVariant { ...@@ -377,6 +387,9 @@ export function getGuidanceVariant(message: string): GuidanceVariant {
if (message.includes('encountered `navigation()`')) { if (message.includes('encountered `navigation()`')) {
return 'navigation' return 'navigation'
} }
if (message.includes('encountered `prefetch()`')) {
return 'prefetch'
}
if ( if (
message.includes('encountered URL data') && message.includes('encountered URL data') &&
!message.includes('encountered uncached data') !message.includes('encountered uncached data')
...@@ -429,14 +442,16 @@ export function isSyncIOClientError(message: string): boolean { ...@@ -429,14 +442,16 @@ export function isSyncIOClientError(message: string): boolean {
return match !== null && match[2] === '-client' return match !== null && match[2] === '-client'
} }
// Detects errors emitted during navigation-phase instant validation: body // Detects Instant Insights emitted during navigation validation. Body errors
// errors from `createRuntimeBodyErrorInNavigation` / // identify the navigation in their message. `prefetch()` and
// `createDynamicBodyErrorInNavigation` (SSR factories instead say "during // `navigation()` in metadata and viewport use dedicated docs URLs
// prerendering"), and validation errors from // because their messages describe the affected API instead of the validation
// `trackDynamicHoleInNavigation` / `getNavigationDisallowedDynamicReasons`. // phase.
export function isBlockingRouteInNavError(message: string): boolean { export function isBlockingRouteInNavError(message: string): boolean {
return ( return (
message.includes('or a navigation') || message.includes('or a navigation') ||
message.includes('/instant-navigation-stage-metadata') ||
message.includes('/instant-navigation-stage-viewport') ||
message.includes('Could not validate `instant`') || message.includes('Could not validate `instant`') ||
message.includes( message.includes(
'Could not validate that a segment in your UI has instant navigation' 'Could not validate that a segment in your UI has instant navigation'
...@@ -477,7 +492,10 @@ export function getBlockingRouteErrorDetails( ...@@ -477,7 +492,10 @@ export function getBlockingRouteErrorDetails(
const isBlockingPageLoadError = const isBlockingPageLoadError =
message.includes('/blocking-prerender-runtime') || message.includes('/blocking-prerender-runtime') ||
message.includes('/blocking-prerender-dynamic') || message.includes('/blocking-prerender-dynamic') ||
message.includes('/instant-shell-url-data') message.includes('/instant-shell-url-data') ||
(message.includes('/instant-navigation-stage') &&
!message.includes('/instant-navigation-stage-metadata') &&
!message.includes('/instant-navigation-stage-viewport'))
if (isBlockingPageLoadError) { if (isBlockingPageLoadError) {
return { return {
type: 'blocking-route', type: 'blocking-route',
...@@ -488,21 +506,33 @@ export function getBlockingRouteErrorDetails( ...@@ -488,21 +506,33 @@ export function getBlockingRouteErrorDetails(
const isDynamicMetadataError = const isDynamicMetadataError =
message.includes('/blocking-prerender-metadata-dynamic') || message.includes('/blocking-prerender-metadata-dynamic') ||
message.includes('/blocking-prerender-metadata-runtime') message.includes('/blocking-prerender-metadata-runtime') ||
message.includes('/instant-navigation-stage-metadata')
if (isDynamicMetadataError) { if (isDynamicMetadataError) {
const variant = getGuidanceVariant(message)
return { return {
type: 'dynamic-metadata', type: 'dynamic-metadata',
variant: getGuidanceVariant(message), variant,
explanation:
variant === 'prefetch' || variant === 'navigation'
? CACHE_STAGE_METADATA_EXPLANATION
: undefined,
} }
} }
const isBlockingViewportError = const isBlockingViewportError =
message.includes('/blocking-prerender-viewport-dynamic') || message.includes('/blocking-prerender-viewport-dynamic') ||
message.includes('/blocking-prerender-viewport-runtime') message.includes('/blocking-prerender-viewport-runtime') ||
message.includes('/instant-navigation-stage-viewport')
if (isBlockingViewportError) { if (isBlockingViewportError) {
const variant = getGuidanceVariant(message)
return { return {
type: 'dynamic-viewport', type: 'dynamic-viewport',
variant: getGuidanceVariant(message), variant,
explanation:
variant === 'prefetch' || variant === 'navigation'
? CACHE_STAGE_VIEWPORT_EXPLANATION
: undefined,
} }
} }
...@@ -578,7 +608,14 @@ export function isInstantNavigationError(error: Error): boolean { ...@@ -578,7 +608,14 @@ export function isInstantNavigationError(error: Error): boolean {
if (getUnrenderedSegmentErrorDetails(error)) return true if (getUnrenderedSegmentErrorDetails(error)) return true
if (getLinkPrefetchPartialErrorDetails(error)) return true if (getLinkPrefetchPartialErrorDetails(error)) return true
const details = getBlockingRouteErrorDetails(error) const details = getBlockingRouteErrorDetails(error)
return details?.type === 'blocking-route' && details.inNavigation if (details?.type === 'blocking-route') return details.inNavigation
if (
details?.type === 'dynamic-metadata' ||
details?.type === 'dynamic-viewport'
) {
return details.variant === 'prefetch' || details.variant === 'navigation'
}
return false
} }
export type ErrorTab = 'errors' | 'instant' export type ErrorTab = 'errors' | 'instant'
...@@ -933,6 +970,13 @@ export function Errors({ ...@@ -933,6 +970,13 @@ export function Errors({
</> </>
) )
break break
case 'prefetch':
errorMessage = (
<>
Next.js encountered <code>prefetch()</code> outside of Suspense.
</>
)
break
case 'dynamic': case 'dynamic':
errorMessage = errorDetails.inNavigation errorMessage = errorDetails.inNavigation
? 'Next.js encountered uncached data during a navigation.' ? 'Next.js encountered uncached data during a navigation.'
...@@ -951,6 +995,7 @@ export function Errors({ ...@@ -951,6 +995,7 @@ export function Errors({
variant={errorDetails.variant} variant={errorDetails.variant}
explanation={ explanation={
errorDetails.variant === 'link' || errorDetails.variant === 'link' ||
errorDetails.variant === 'prefetch' ||
errorDetails.variant === 'navigation' errorDetails.variant === 'navigation'
? BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION ? BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION
: errorDetails.inNavigation : errorDetails.inNavigation
...@@ -1098,6 +1143,14 @@ export function Errors({ ...@@ -1098,6 +1143,14 @@ export function Errors({
</> </>
) )
break break
case 'prefetch':
errorMessage = (
<>
Next.js encountered <code>prefetch()</code> in{' '}
<code>generateMetadata()</code>.
</>
)
break
case 'dynamic': case 'dynamic':
errorMessage = ( errorMessage = (
<> <>
...@@ -1117,6 +1170,7 @@ export function Errors({ ...@@ -1117,6 +1170,7 @@ export function Errors({
<InstantHeaderExplanation <InstantHeaderExplanation
kind="metadata" kind="metadata"
variant={errorDetails.variant} variant={errorDetails.variant}
explanation={errorDetails.explanation}
/> />
} }
renderTabBar={renderTabBar} renderTabBar={renderTabBar}
...@@ -1173,6 +1227,14 @@ export function Errors({ ...@@ -1173,6 +1227,14 @@ export function Errors({
</> </>
) )
break break
case 'prefetch':
errorMessage = (
<>
Next.js encountered <code>prefetch()</code> in{' '}
<code>generateViewport()</code>.
</>
)
break
case 'dynamic': case 'dynamic':
errorMessage = ( errorMessage = (
<> <>
...@@ -1193,6 +1255,7 @@ export function Errors({ ...@@ -1193,6 +1255,7 @@ export function Errors({
<InstantHeaderExplanation <InstantHeaderExplanation
kind="viewport" kind="viewport"
variant={errorDetails.variant} variant={errorDetails.variant}
explanation={errorDetails.explanation}
/> />
} }
renderTabBar={renderTabBar} renderTabBar={renderTabBar}
......
...@@ -94,6 +94,14 @@ export function FixCardArrowUpIcon() { ...@@ -94,6 +94,14 @@ export function FixCardArrowUpIcon() {
) )
} }
export function FixCardCheckIcon() {
return (
<svg {...ICON_PROPS}>
<path d="M5 12l4 4L19 6" />
</svg>
)
}
export function FixCardMinusIcon() { export function FixCardMinusIcon() {
return ( return (
<svg {...ICON_PROPS}> <svg {...ICON_PROPS}>
......
...@@ -2,6 +2,8 @@ import { ...@@ -2,6 +2,8 @@ import {
createDynamicBodyError, createDynamicBodyError,
createDynamicBodyErrorInNavigation, createDynamicBodyErrorInNavigation,
createLinkBodyErrorInNavigation, createLinkBodyErrorInNavigation,
createNavigationMetadataError,
createPrefetchViewportError,
createRuntimeBodyError, createRuntimeBodyError,
createRuntimeBodyErrorInNavigation, createRuntimeBodyErrorInNavigation,
} from '../../server/app-render/blocking-route-messages' } from '../../server/app-render/blocking-route-messages'
...@@ -162,6 +164,15 @@ describe('getInstantErrorRoute', () => { ...@@ -162,6 +164,15 @@ describe('getInstantErrorRoute', () => {
).toBe(DYNAMIC_ROUTE_TEMPLATE) ).toBe(DYNAMIC_ROUTE_TEMPLATE)
}) })
it('returns the route for cache stage metadata and viewport Insights', () => {
expect(
getInstantErrorRoute(createNavigationMetadataError(STATIC_ROUTE))
).toBe(STATIC_ROUTE)
expect(
getInstantErrorRoute(createPrefetchViewportError(DYNAMIC_ROUTE_TEMPLATE))
).toBe(DYNAMIC_ROUTE_TEMPLATE)
})
it('returns the route for the unrendered-segment wrapper', () => { it('returns the route for the unrendered-segment wrapper', () => {
const error = new Error( const error = new Error(
`Route "${STATIC_ROUTE}": Could not validate that a segment in your UI has instant navigation.\n\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.\n\nDropped segment:\n app/example/page.tsx` `Route "${STATIC_ROUTE}": Could not validate that a segment in your UI has instant navigation.\n\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.\n\nDropped segment:\n app/example/page.tsx`
......
...@@ -44,14 +44,24 @@ export function createLinkBodyErrorInNavigation(route: string): Error { ...@@ -44,14 +44,24 @@ export function createLinkBodyErrorInNavigation(route: string): Error {
} }
export function createNavigationBodyErrorInNavigation(route: string): Error { export function createNavigationBodyErrorInNavigation(route: string): Error {
// TODO(cache-stages): docs link
return new Error( return new Error(
`Route "${route}": Next.js encountered \`navigation()\` during prerendering or a navigation.\n\n` + `Route "${route}": Next.js encountered \`navigation()\` during prerendering or a navigation.\n\n` +
`\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` + `\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` + `Ways to fix this:\n` +
` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` + ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the component that calls \`navigation()\`\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-shell-url-data` `Learn more: https://nextjs.org/docs/messages/instant-navigation-stage`
)
}
export function createPrefetchBodyErrorInNavigation(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered \`prefetch()\` during prerendering or a navigation.\n\n` +
`\`prefetch()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the component that calls \`prefetch()\`\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-navigation-stage`
) )
} }
...@@ -107,14 +117,24 @@ export function createRuntimeMetadataError(route: string): Error { ...@@ -107,14 +117,24 @@ export function createRuntimeMetadataError(route: string): Error {
} }
export function createNavigationMetadataError(route: string): Error { export function createNavigationMetadataError(route: string): Error {
// TODO(cache-stages): docs link
return new Error( return new Error(
`Route "${route}": Next.js encountered \`navigation()\` in \`generateMetadata()\`.\n\n` + `Route "${route}": Next.js encountered \`navigation()\` in \`generateMetadata()\`.\n\n` +
`This route's metadata is blocked, but the rest of its content can be prefetched. \`navigation()\` called in \`generateMetadata()\` prevents it from being prefetched.\n\n` + `Metadata can already stream without blocking the route's UI, so delaying it until navigation may be unintentional.\n\n` +
`Ways to fix this:\n` + `Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` + ` - [remove] Remove \`navigation()\` from \`generateMetadata()\`\n` +
` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` + ` - [mark] Render a marker component that calls \`await navigation()\` inside \`<Suspense>\` on the page\n\n` +
`Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime` `Learn more: https://nextjs.org/docs/messages/instant-navigation-stage-metadata`
)
}
export function createPrefetchMetadataError(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered \`prefetch()\` in \`generateMetadata()\`.\n\n` +
`Metadata can already stream without blocking the route's UI, so delaying it until a per-link prefetch or navigation may be unintentional.\n\n` +
`Ways to fix this:\n` +
` - [remove] Remove \`prefetch()\` from \`generateMetadata()\`\n` +
` - [mark] Render a marker component that calls \`await prefetch()\` inside \`<Suspense>\` on the page\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-navigation-stage-metadata`
) )
} }
...@@ -152,14 +172,24 @@ export function createRuntimeViewportError(route: string): Error { ...@@ -152,14 +172,24 @@ export function createRuntimeViewportError(route: string): Error {
} }
export function createNavigationViewportError(route: string): Error { export function createNavigationViewportError(route: string): Error {
// TODO(cache-stages): docs link
return new Error( return new Error(
`Route "${route}": Next.js encountered \`navigation()\` in \`generateViewport()\`.\n\n` + `Route "${route}": Next.js encountered \`navigation()\` in \`generateViewport()\`.\n\n` +
`\`navigation()\` in \`generateViewport()\` prevents creating a shell, leading to a slower user experience.\n\n` + `This prevents Next.js from creating the App Shell, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` + `Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` + ` - [remove] Remove \`navigation()\` from \`generateViewport()\`\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ` - [ignore] Set \`export const instant = false\` to disable validation for this segment\n\n` +
`Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime` `Learn more: https://nextjs.org/docs/messages/instant-navigation-stage-viewport`
)
}
export function createPrefetchViewportError(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered \`prefetch()\` in \`generateViewport()\`.\n\n` +
`This prevents Next.js from creating the App Shell, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [remove] Remove \`prefetch()\` from \`generateViewport()\`\n` +
` - [ignore] Set \`export const instant = false\` to disable validation for this segment\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-navigation-stage-viewport`
) )
} }
......
...@@ -49,12 +49,14 @@ import { ...@@ -49,12 +49,14 @@ import {
createDynamicBodyError, createDynamicBodyError,
createRuntimeBodyErrorInNavigation, createRuntimeBodyErrorInNavigation,
createNavigationBodyErrorInNavigation, createNavigationBodyErrorInNavigation,
createPrefetchBodyErrorInNavigation,
createDynamicBodyErrorInNavigation, createDynamicBodyErrorInNavigation,
createDynamicOrRuntimeBodyError, createDynamicOrRuntimeBodyError,
createRuntimeMetadataError, createRuntimeMetadataError,
createDynamicMetadataError, createDynamicMetadataError,
createRuntimeViewportError, createRuntimeViewportError,
createNavigationViewportError, createNavigationViewportError,
createPrefetchViewportError,
createDynamicViewportError, createDynamicViewportError,
createDynamicOrRuntimeViewportError, createDynamicOrRuntimeViewportError,
createDynamicOrRuntimeMetadataError, createDynamicOrRuntimeMetadataError,
...@@ -63,6 +65,7 @@ import { ...@@ -63,6 +65,7 @@ import {
createLinkMetadataError, createLinkMetadataError,
createLinkViewportError, createLinkViewportError,
createNavigationMetadataError, createNavigationMetadataError,
createPrefetchMetadataError,
createNonPrerenderableMetadataErrorInStaticRoute, createNonPrerenderableMetadataErrorInStaticRoute,
createNonPrerenderableViewportErrorInStaticRoute, createNonPrerenderableViewportErrorInStaticRoute,
createNonPrerenderableBodyErrorInStaticRoute, createNonPrerenderableBodyErrorInStaticRoute,
...@@ -806,10 +809,12 @@ export enum DynamicHoleKind { ...@@ -806,10 +809,12 @@ export enum DynamicHoleKind {
Link = 2, Link = 2,
/** We know that this hole is caused by navigation(). */ /** We know that this hole is caused by navigation(). */
Navigation = 3, Navigation = 3,
/** We know that this hole is caused by prefetch(). */
Prefetch = 4,
/** We know that this hole is caused by dynamic data. */ /** We know that this hole is caused by dynamic data. */
Dynamic = 4, Dynamic = 5,
/** We know that this hole is caused by runtime or dynamic data, but don't know which. */ /** We know that this hole is caused by runtime or dynamic data, but don't know which. */
RuntimeOrDynamic = 5, RuntimeOrDynamic = 6,
} }
// In Instant Validation we can always discriminate between runtime and dynamic. // In Instant Validation we can always discriminate between runtime and dynamic.
...@@ -1012,6 +1017,8 @@ function createBodyErrorInNavigation( ...@@ -1012,6 +1017,8 @@ function createBodyErrorInNavigation(
return createLinkBodyErrorInNavigation(route) return createLinkBodyErrorInNavigation(route)
case DynamicHoleKind.Navigation: case DynamicHoleKind.Navigation:
return createNavigationBodyErrorInNavigation(route) return createNavigationBodyErrorInNavigation(route)
case DynamicHoleKind.Prefetch:
return createPrefetchBodyErrorInNavigation(route)
case DynamicHoleKind.Dynamic: case DynamicHoleKind.Dynamic:
return createDynamicBodyErrorInNavigation(route) return createDynamicBodyErrorInNavigation(route)
} }
...@@ -1025,6 +1032,8 @@ function createMetadataError(kind: DynamicHoleKind, route: string): Error { ...@@ -1025,6 +1032,8 @@ function createMetadataError(kind: DynamicHoleKind, route: string): Error {
return createLinkMetadataError(route) return createLinkMetadataError(route)
case DynamicHoleKind.Navigation: case DynamicHoleKind.Navigation:
return createNavigationMetadataError(route) return createNavigationMetadataError(route)
case DynamicHoleKind.Prefetch:
return createPrefetchMetadataError(route)
case DynamicHoleKind.Dynamic: case DynamicHoleKind.Dynamic:
return createDynamicMetadataError(route) return createDynamicMetadataError(route)
case DynamicHoleKind.RuntimeOrDynamic: case DynamicHoleKind.RuntimeOrDynamic:
...@@ -1040,6 +1049,8 @@ function createViewportError(kind: DynamicHoleKind, route: string): Error { ...@@ -1040,6 +1049,8 @@ function createViewportError(kind: DynamicHoleKind, route: string): Error {
return createLinkViewportError(route) return createLinkViewportError(route)
case DynamicHoleKind.Navigation: case DynamicHoleKind.Navigation:
return createNavigationViewportError(route) return createNavigationViewportError(route)
case DynamicHoleKind.Prefetch:
return createPrefetchViewportError(route)
case DynamicHoleKind.Dynamic: case DynamicHoleKind.Dynamic:
return createDynamicViewportError(route) return createDynamicViewportError(route)
case DynamicHoleKind.RuntimeOrDynamic: case DynamicHoleKind.RuntimeOrDynamic:
......
...@@ -204,6 +204,7 @@ export async function collectStagedSegmentData( ...@@ -204,6 +204,7 @@ export async function collectStagedSegmentData(
case ValidationPrefetchKind.StaticAppShell: { case ValidationPrefetchKind.StaticAppShell: {
partialStages = [ partialStages = [
RenderStage.ShellStatic, RenderStage.ShellStatic,
RenderStage.PrefetchStatic_prefetchApi,
RenderStage.PrefetchStatic, RenderStage.PrefetchStatic,
RenderStage.NavigationStatic, // TODO(cache-stages): only if needed RenderStage.NavigationStatic, // TODO(cache-stages): only if needed
RenderStage.PrefetchRuntime, RenderStage.PrefetchRuntime,
...@@ -213,6 +214,7 @@ export async function collectStagedSegmentData( ...@@ -213,6 +214,7 @@ export async function collectStagedSegmentData(
case ValidationPrefetchKind.RuntimeAppShell: { case ValidationPrefetchKind.RuntimeAppShell: {
partialStages = [ partialStages = [
RenderStage.ShellRuntime, RenderStage.ShellRuntime,
RenderStage.PrefetchRuntime_prefetchApi,
RenderStage.PrefetchRuntime, RenderStage.PrefetchRuntime,
RenderStage.NavigationRuntime, // TODO(cache-stages): only if needed RenderStage.NavigationRuntime, // TODO(cache-stages): only if needed
] ]
...@@ -288,11 +290,13 @@ async function collectSegmentDataForStage( ...@@ -288,11 +290,13 @@ async function collectSegmentDataForStage(
switch (currentStage) { switch (currentStage) {
case RenderStage.Before: case RenderStage.Before:
case RenderStage.ShellStatic: case RenderStage.ShellStatic:
case RenderStage.PrefetchStatic_prefetchApi:
case RenderStage.PrefetchStatic: case RenderStage.PrefetchStatic:
case RenderStage.Static: case RenderStage.Static:
case RenderStage.NavigationStatic: case RenderStage.NavigationStatic:
return 'Prerender' return 'Prerender'
case RenderStage.ShellRuntime: // TODO(app-shells) - proper environmentName case RenderStage.ShellRuntime: // TODO(app-shells) - proper environmentName
case RenderStage.PrefetchRuntime_prefetchApi:
case RenderStage.PrefetchRuntime: case RenderStage.PrefetchRuntime:
case RenderStage.NavigationRuntime: case RenderStage.NavigationRuntime:
return 'Prefetch' return 'Prefetch'
...@@ -1024,6 +1028,7 @@ export async function createCombinedPayloadAtDepth( ...@@ -1024,6 +1028,7 @@ export async function createCombinedPayloadAtDepth(
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
overrideStageForPartialSegments: overrideStageForPartialSegments:
| null | null
| RenderStage.PrefetchRuntime_prefetchApi
| RenderStage.PrefetchRuntime | RenderStage.PrefetchRuntime
| RenderStage.NavigationRuntime | RenderStage.NavigationRuntime
): Promise<ValidationPayloadResult | null> { ): Promise<ValidationPayloadResult | null> {
......
...@@ -5,13 +5,17 @@ export enum RenderStage { ...@@ -5,13 +5,17 @@ export enum RenderStage {
Before = 1, Before = 1,
// //
ShellStatic = 10, ShellStatic = 10,
PrefetchStatic = 11, /** Discrimination-only stage: `prefetch()` in validation renders (static) */
NavigationStatic = 12, PrefetchStatic_prefetchApi = 11,
Static = 13, PrefetchStatic = 12,
NavigationStatic = 13,
Static = 14,
// //
ShellRuntime = 20, ShellRuntime = 20,
PrefetchRuntime = 21, /** Discrimination-only stage: `prefetch()` in validation renders (runtime) */
NavigationRuntime = 22, PrefetchRuntime_prefetchApi = 21,
PrefetchRuntime = 22,
NavigationRuntime = 23,
// //
Dynamic = 30, Dynamic = 30,
Abandoned = 40, Abandoned = 40,
...@@ -24,11 +28,13 @@ export type AdvanceableRenderStage = Exclude< ...@@ -24,11 +28,13 @@ export type AdvanceableRenderStage = Exclude<
export const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [ export const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [
RenderStage.ShellStatic, RenderStage.ShellStatic,
RenderStage.PrefetchStatic_prefetchApi,
RenderStage.PrefetchStatic, RenderStage.PrefetchStatic,
RenderStage.NavigationStatic, RenderStage.NavigationStatic,
RenderStage.Static, RenderStage.Static,
// //
RenderStage.ShellRuntime, RenderStage.ShellRuntime,
RenderStage.PrefetchRuntime_prefetchApi,
RenderStage.PrefetchRuntime, RenderStage.PrefetchRuntime,
RenderStage.NavigationRuntime, RenderStage.NavigationRuntime,
// //
......
...@@ -746,8 +746,30 @@ class TrackedPromise<T> extends Promise<T> { ...@@ -746,8 +746,30 @@ class TrackedPromise<T> extends Promise<T> {
export const RENDER_STAGES_BY_DATA_KIND = { export const RENDER_STAGES_BY_DATA_KIND = {
sessionData: RenderStage.ShellRuntime as const, sessionData: RenderStage.ShellRuntime as const,
staticLinkData: RenderStage.PrefetchStatic as const, /**
runtimeLinkData: RenderStage.PrefetchRuntime as const, * Statically-prerenderable URL data, like static `params`.
* It may need to be pushed to a runtime stage in a runtime prerender,
* but it's semantically distinct from `runtimeUrlData` like `searchParams`,
* which is always excluded from static prerenders.
* */
staticUrlData: {
/**
* From that app's point of view, `prefetch()` is semantically the same as
* `staticUrlData`, because it does not resolve in a shell but resolves in
* a prefetch (even a static one).
* We handle it separately to provide a specialized error in validation renders.
*/
prefetchApi: {
static: RenderStage.PrefetchStatic_prefetchApi as const,
runtime: RenderStage.PrefetchRuntime_prefetchApi as const,
},
static: RenderStage.PrefetchStatic as const,
runtime: RenderStage.PrefetchRuntime as const,
},
/**
* URL data that is never statically-prerenderable, like static `searchParams`.
* */
runtimeUrlData: RenderStage.PrefetchRuntime as const,
} }
export function applyOwnerStack(error: Error): Error { export function applyOwnerStack(error: Error): Error {
......
...@@ -61,6 +61,7 @@ export function io(expression: string, type: SyncIOApiType) { ...@@ -61,6 +61,7 @@ export function io(expression: string, type: SyncIOApiType) {
// `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason` // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`
switch (stageController.currentStage) { switch (stageController.currentStage) {
case RenderStage.ShellStatic: case RenderStage.ShellStatic:
case RenderStage.PrefetchStatic_prefetchApi:
case RenderStage.PrefetchStatic: case RenderStage.PrefetchStatic:
case RenderStage.NavigationStatic: case RenderStage.NavigationStatic:
case RenderStage.Static: { case RenderStage.Static: {
...@@ -68,6 +69,7 @@ export function io(expression: string, type: SyncIOApiType) { ...@@ -68,6 +69,7 @@ export function io(expression: string, type: SyncIOApiType) {
break break
} }
case RenderStage.ShellRuntime: case RenderStage.ShellRuntime:
case RenderStage.PrefetchRuntime_prefetchApi:
case RenderStage.PrefetchRuntime: case RenderStage.PrefetchRuntime:
case RenderStage.NavigationRuntime: { case RenderStage.NavigationRuntime: {
// We're in a runtime stage. // We're in a runtime stage.
......
...@@ -46,11 +46,14 @@ export function prefetch(): Promise<void> { ...@@ -46,11 +46,14 @@ export function prefetch(): Promise<void> {
) )
} }
const stageVariants = RENDER_STAGES_BY_DATA_KIND.staticUrlData.prefetchApi
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': { case 'prerender': {
// Content below `prefetch()` is excluded from the shell, but it's // Content below `prefetch()` is excluded from the shell, but it's
// deliberately included in the static output (and thus in static // deliberately included in the static output (and thus in static
// prefetches), so we only delay it until the static prefetch stage. // prefetches), so we only delay it until the static prefetch stage.
// It resolves in `PrefetchStatic_prefetchApi`, one stage ahead of URL data,
// so validation can attribute a blocking hole to `prefetch()`.
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
...@@ -59,7 +62,7 @@ export function prefetch(): Promise<void> { ...@@ -59,7 +62,7 @@ export function prefetch(): Promise<void> {
} else { } else {
// Final prerender // Final prerender
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.staticLinkData, stageVariants.static,
'prefetch', 'prefetch',
undefined undefined
) )
...@@ -67,12 +70,12 @@ export function prefetch(): Promise<void> { ...@@ -67,12 +70,12 @@ export function prefetch(): Promise<void> {
} }
case 'prerender-runtime': { case 'prerender-runtime': {
// In a shell render, prefetch() doesn't resolve, because it doesn't reach // In a shell render, prefetch() doesn't resolve, because it doesn't reach
// `Runtime`. It'll resolve in a runtime prefetch, and in a runtime // `PrefetchRuntime`. It'll resolve in a runtime prefetch, and in a runtime
// prerender produced during a navigation. // prerender produced during a navigation.
// Note that this does not mark the subtree as dynamic -- content guarded by // Note that this does not mark the subtree as dynamic -- content guarded by
// prefetch() is still considered cacheable. // prefetch() is still considered cacheable.
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
const prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData const prefetchStage = stageVariants.runtime
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
// Make sure we don't unblock content that won't be reached in the final prerender. // Make sure we don't unblock content that won't be reached in the final prerender.
...@@ -99,9 +102,12 @@ export function prefetch(): Promise<void> { ...@@ -99,9 +102,12 @@ export function prefetch(): Promise<void> {
if (stagedRendering) { if (stagedRendering) {
// We can either recover a static shell or a runtime shell, but not both. // We can either recover a static shell or a runtime shell, but not both.
trackIncompatibleShellContent(workUnitStore, '`prefetch()`') trackIncompatibleShellContent(workUnitStore, '`prefetch()`')
const stage = workUnitStore.needsRuntimeShell const stage =
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData // Match the timing of 'prerender-runtime'. stageVariants[
: RENDER_STAGES_BY_DATA_KIND.staticLinkData // Match the timing of 'prerender'. workUnitStore.needsRuntimeShell
? 'runtime' // Match the timing of 'prerender-runtime'.
: 'static' // Match the timing of 'prerender'.
]
return stagedRendering.delayUntilStage(stage, 'prefetch', undefined) return stagedRendering.delayUntilStage(stage, 'prefetch', undefined)
} }
......
...@@ -358,7 +358,8 @@ function createStaticPrerenderParams( ...@@ -358,7 +358,8 @@ function createStaticPrerenderParams(
if ( if (
!allParamsAreRootParams(underlyingParams, prerenderStore.rootParams) !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)
) { ) {
const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData const staticParamsStage =
RENDER_STAGES_BY_DATA_KIND.staticUrlData.static
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
staticParamsStage, staticParamsStage,
'params', 'params',
...@@ -434,7 +435,7 @@ function createRuntimePrerenderParams( ...@@ -434,7 +435,7 @@ function createRuntimePrerenderParams(
// Non-root params are URL data, and we need to recover a param-less session shell, // Non-root params are URL data, and we need to recover a param-less session shell,
// so we delay all params until the PrefetchRuntime stage (even if they're static) // so we delay all params until the PrefetchRuntime stage (even if they're static)
const paramsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData const paramsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
...@@ -575,9 +576,10 @@ function createStagedRenderParamsImpl( ...@@ -575,9 +576,10 @@ function createStagedRenderParamsImpl(
// shells are handled with a separate render. // shells are handled with a separate render.
// However, in dev we might need to recover a session shell for instant validation. // However, in dev we might need to recover a session shell for instant validation.
// This is indicated by `needsRuntimeShell`. // This is indicated by `needsRuntimeShell`.
const staticParamsStage = workUnitStore.needsRuntimeShell const staticParamsStage =
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData RENDER_STAGES_BY_DATA_KIND.staticUrlData[
: RENDER_STAGES_BY_DATA_KIND.staticLinkData workUnitStore.needsRuntimeShell ? 'runtime' : 'static'
]
const promise = stagedRendering.delayUntilStage( const promise = stagedRendering.delayUntilStage(
staticParamsStage, staticParamsStage,
...@@ -771,7 +773,7 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -771,7 +773,7 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
? makeDevtoolsIOAwarePromise( ? makeDevtoolsIOAwarePromise(
userspaceParams, userspaceParams,
requestStore, requestStore,
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
) )
: // We don't want to force an environment transition when this params is not part of the fallback params set : // We don't want to force an environment transition when this params is not part of the fallback params set
Promise.resolve(userspaceParams) Promise.resolve(userspaceParams)
......
...@@ -57,7 +57,7 @@ export function createServerPathnameForMetadata( ...@@ -57,7 +57,7 @@ export function createServerPathnameForMetadata(
// behavior of always resolving in the PrefetchRuntime stage // behavior of always resolving in the PrefetchRuntime stage
// (i.e. assuming that we have non-static params in the pathname) // (i.e. assuming that we have non-static params in the pathname)
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
if (stagedRendering) { if (stagedRendering) {
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
pathnameStage, pathnameStage,
......
...@@ -245,7 +245,7 @@ function createRuntimePrerenderSearchParams( ...@@ -245,7 +245,7 @@ function createRuntimePrerenderSearchParams(
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams) ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
: underlyingSearchParams : underlyingSearchParams
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
...@@ -596,7 +596,7 @@ function makeUntrackedSearchParamsWithDevWarningsImpl( ...@@ -596,7 +596,7 @@ function makeUntrackedSearchParamsWithDevWarningsImpl(
const promise = makeDevtoolsIOAwarePromise( const promise = makeDevtoolsIOAwarePromise(
proxiedUnderlying, proxiedUnderlying,
requestStore, requestStore,
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
) )
promise.then( promise.then(
......
...@@ -2734,9 +2734,10 @@ export async function cache( ...@@ -2734,9 +2734,10 @@ export async function cache(
// This entry cannot be part of the shell, so we delay it to the prefetch. // This entry cannot be part of the shell, so we delay it to the prefetch.
let prefetchStage: AdvanceableRenderStage let prefetchStage: AdvanceableRenderStage
if (prerenderStore.type === 'prerender') { if (prerenderStore.type === 'prerender') {
prefetchStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData prefetchStage =
RENDER_STAGES_BY_DATA_KIND.staticUrlData.static
} else { } else {
prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData
} }
if ( if (
// If the prerender ends before the prefetch stage (because // If the prerender ends before the prefetch stage (because
...@@ -2795,16 +2796,17 @@ export async function cache( ...@@ -2795,16 +2796,17 @@ export async function cache(
stage = RenderStage.Dynamic stage = RenderStage.Dynamic
} else { } else {
// If the entry would be be excluded from the shell, treat it as // If the entry would be be excluded from the shell, treat it as
// if it were link data. // if it were static URL data.
// (Note that this is still correct without PPF or in static shell validation, // (Note that this is still correct without PPF or in static shell validation,
// where we don't use runtime shells and include static link data) // where we don't use runtime shells and include static URL data)
trackIncompatibleShellContent( trackIncompatibleShellContent(
workUnitStore, workUnitStore,
'"use cache" excluded from app shells due to a short staletime' '"use cache" excluded from app shells due to a short staletime'
) )
stage = workUnitStore.needsRuntimeShell stage =
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData RENDER_STAGES_BY_DATA_KIND.staticUrlData[
: RENDER_STAGES_BY_DATA_KIND.staticLinkData workUnitStore.needsRuntimeShell ? 'runtime' : 'static'
]
} }
debug?.( debug?.(
logPrefix, logPrefix,
...@@ -3442,16 +3444,17 @@ export async function cache( ...@@ -3442,16 +3444,17 @@ export async function cache(
stage = RenderStage.Dynamic stage = RenderStage.Dynamic
} else { } else {
// If the entry would be be excluded from the shell, treat it as // If the entry would be be excluded from the shell, treat it as
// if it were link data. // if it were static URL data.
// (Note that this is still correct without PPF or in static shell validation, // (Note that this is still correct without PPF or in static shell validation,
// where we don't use runtime shells and include static link data) // where we don't use runtime shells and include static URL data)
trackIncompatibleShellContent( trackIncompatibleShellContent(
workUnitStore, workUnitStore,
'"use cache" excluded from app shells due to a short staletime' '"use cache" excluded from app shells due to a short staletime'
) )
stage = workUnitStore.needsRuntimeShell stage =
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData RENDER_STAGES_BY_DATA_KIND.staticUrlData[
: RENDER_STAGES_BY_DATA_KIND.staticLinkData workUnitStore.needsRuntimeShell ? 'runtime' : 'static'
]
} }
debug?.( debug?.(
logPrefix, logPrefix,
......
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