Replicate production prefetch shells for instant navigations in dev

The Instant Navigation lock makes a development render reflect the
route's prefetched state: while the lock is held, a navigation should
show only what was prefetched and keep navigation-time data deferred.
Both the `instant()` testing API from `@next/playwright` and the Instant
Navigation devtools rely on it. The development render did not match
what a production build serves in three ways: a route that blocks
outside a `<Suspense>` boundary leaked its data instead of staying
parked, the shell did not defer params the way a production prefetch
would, and the data a runtime prefetch resolves did not surface inside
the scope.

While the lock is held, the app render now permits an empty static
shell. A route that reads dynamic data such as `cookies()` outside any
`<Suspense>` boundary has no static shell, so the on-demand render
previously threw a static generation bailout, served an error page, and
entered a `/_tree` redirect loop that committed the blocked data.
Permitting an empty shell lets the render emit the shell instead. The
override is scoped to the prefetch render made while the lock is held, a
document request or a `'1'` static prefetch; a regular dynamic
navigation, including the one that commits once the lock releases, runs
without it. So the validation that flags a blocking route is not
weakened: production validation runs at build time, and the development
validation still runs and is shown in the dev overlay.

The development fallback-shell render now reads the per-URL
`fallbackParams` request meta that the server derives for the requested
URL, so the instant shell defers exactly the params a production
prefetch would: `generateStaticParams`-covered params resolve in the
shell and only the uncovered ones are deferred. When the URL is fully
covered the meta is absent and nothing is deferred. That per-URL
computation is introduced by the preceding change in this stack, and
this change depends on it: with the earlier fewest-param heuristic,
three of the instant-navigation tests fail.

Under the Instant Navigation lock the captured shell should reflect the
fully settled prefetched state, what the route would look like once
every in-flight prefetch has landed. The segment cache normally prefers
a ready entry over a more-specific in-flight one so a real navigation is
not stalled, but under the lock that ready entry can be a less-specific,
stale shell while a more-specific prefetch is still resolving. So under
the lock it now prefers the more-specific in-flight entry, which is what
produces the complete settled picture: the data a runtime prefetch
resolves (dynamic params among other runtime-stage reads) surfaces
inside the scope, and a blocked navigation into a deeper fallback
segment stays parked on the committed shell instead of committing a
stale resolved entry. This matches the best case in production, where
the runtime prefetch has written its entry before the navigation reads
it.

Enabling App Shells in the default fixture makes the app shell carry a
cookie that is read with no preceding param access, so the existing
client-navigation cookie test is updated to assert the cookie is present
in the instant shell, alongside a new param-gated variation that asserts
it is excluded when a param is read first. New cases cover mixed static
and fallback params under both a normal navigation and a runtime
prefetch, and a deeper-segment blocking navigation that must stay parked
on the committed parent. A blocking route that reads request data
outside any `<Suspense>` boundary cannot be built for production, so it
is isolated in a development-only fixture and guarded so the production
job registers only a placeholder.
parent 0124d704
...@@ -797,8 +797,10 @@ export async function handler( ...@@ -797,8 +797,10 @@ export async function handler(
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
forceStaticRender, forceStaticRender,
allowEmptyStaticShell,
}: { }: {
span?: Span span?: Span
allowEmptyStaticShell?: boolean
/** /**
* The postponed data for this render. This is only provided when resuming * The postponed data for this render. This is only provided when resuming
...@@ -845,6 +847,7 @@ export async function handler( ...@@ -845,6 +847,7 @@ export async function handler(
routeModule, routeModule,
page: srcPage, page: srcPage,
postponed, postponed,
allowEmptyStaticShell,
shouldWaitOnAllReady, shouldWaitOnAllReady,
serveStreamingMetadata, serveStreamingMetadata,
supportsDynamicResponse: supportsDynamicResponse:
...@@ -1167,22 +1170,33 @@ export async function handler( ...@@ -1167,22 +1170,33 @@ export async function handler(
fallbackRouteParams = null fallbackRouteParams = null
} }
} else { } else {
// In dev, the prerender manifest isn't populated for ad-hoc // In dev the prerender manifest isn't populated for ad-hoc
// prefetches. The outer `!isPrerendered` guard means every URL // prefetches (`fallbackMode` is undefined for not-fully-generated
// reaching this block has params not covered by // routes, so the on-demand manifest write is skipped, and
// `generateStaticParams`, so the worst-case fallback set — // `getPrerenderManifest` is cached regardless). So
// every dynamic segment from the loader tree — matches what a // `prerenderInfo` is unavailable here. Instead base-server
// static prerender would use. This keeps the prefetch response // derives the per-URL fallback set from the dev `getStaticPaths`
// from baking resolved param values into the shell. // result and threads it via the `fallbackParams` request meta —
// // the most-specific prerendered route matching this URL, so
// `isDebugStaticShell` covers the `?__nextppronly=1` query and // `generateStaticParams`-covered params resolve in the shell and
// the Instant Navigation testing cookie; `isDebugFallbackShell` // only the uncovered ones are deferred, matching what a
// is the explicit fallback-shell debug flow. // production build serves. `isDebugFallbackShell` (the explicit
if (isDebugStaticShell || isDebugFallbackShell) { // fallback-shell debug flow) still forces the worst case.
if (isDebugFallbackShell) {
fallbackRouteParams = getFallbackRouteParams( fallbackRouteParams = getFallbackRouteParams(
normalizedSrcPage, normalizedSrcPage,
routeModule routeModule
) )
} else if (isDebugStaticShell) {
// base-server threads the per-URL fallback set via the
// `fallbackParams` meta for every dev Cache Components dynamic
// request, so reuse it as the fallback route params for this
// shell render. It only sets the meta for routes that still
// have uncovered params, so an absent meta means this URL is
// fully covered by `generateStaticParams` and there is nothing
// to defer (`null`).
fallbackRouteParams =
getRequestMeta(req, 'fallbackParams') ?? null
} else { } else {
fallbackRouteParams = null fallbackRouteParams = null
} }
...@@ -1217,6 +1231,7 @@ export async function handler( ...@@ -1217,6 +1231,7 @@ export async function handler(
// more specific cache entry for later requests. // more specific cache entry for later requests.
fallbackRouteParams, fallbackRouteParams,
forceStaticRender: true, forceStaticRender: true,
allowEmptyStaticShell: isInstantNavigationTest || undefined,
}), }),
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
isMinimalMode, isMinimalMode,
...@@ -1495,6 +1510,7 @@ export async function handler( ...@@ -1495,6 +1510,7 @@ export async function handler(
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
forceStaticRender, forceStaticRender,
allowEmptyStaticShell: isInstantNavigationTest || undefined,
}) })
} catch (err) { } catch (err) {
// if this is a background revalidate we need to report // if this is a background revalidate we need to report
......
...@@ -486,6 +486,15 @@ export function readSegmentCacheEntry( ...@@ -486,6 +486,15 @@ export function readSegmentCacheEntry(
) )
} }
function isInstantNavigationLocked(): boolean {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
return isNavigationLocked()
}
return false
}
/** /**
* Like `readSegmentCacheEntry`, but prefers a Fulfilled entry over a * Like `readSegmentCacheEntry`, but prefers a Fulfilled entry over a
* more-specific Pending or Rejected entry. Use this during a navigation, where * more-specific Pending or Rejected entry. Use this during a navigation, where
...@@ -493,6 +502,10 @@ export function readSegmentCacheEntry( ...@@ -493,6 +502,10 @@ export function readSegmentCacheEntry(
* immediately rather than blocking on a more-specific Pending entry that may * immediately rather than blocking on a more-specific Pending entry that may
* still be in-flight. * still be in-flight.
* *
* Exception: while an Instant Navigation Testing lock is held, a more-specific
* Pending entry is preferred (see body) so the capture waits for an in-flight
* runtime prefetch instead of committing a less-specific fallback shell.
*
* Performs up to two lookups: * Performs up to two lookups:
* 1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries * 1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries
* at more-specific keypaths to find a Fulfilled fallback (e.g. a cached * at more-specific keypaths to find a Fulfilled fallback (e.g. a cached
...@@ -514,6 +527,34 @@ export function readSegmentCacheEntryForNavigation( ...@@ -514,6 +527,34 @@ export function readSegmentCacheEntryForNavigation(
true true
) )
if (fulfilled !== null) { if (fulfilled !== null) {
if (process.env.__NEXT_EXPOSE_TESTING_API && isInstantNavigationLocked()) {
// While an Instant Navigation Testing lock is held, the capture should
// reflect the fully-prefetched state. Normally we prefer a ready
// (Fulfilled) shell over a more-specific in-flight (Pending) entry so a
// real navigation isn't stalled. But under the lock that fallback shell
// can be a less-specific entry (e.g. a static prefetch with the
// runtime-stage data, such as dynamic params, deferred) while a
// more-specific runtime prefetch is still in flight. In that case we want
// to wait for the runtime prefetch so the data it resolves surfaces
// inside the instant scope, matching the best case in production, where
// the runtime prefetch has written its entry before the navigation reads
// it. So if a more-specific Pending entry exists, prefer it.
const mostSpecific = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
varyPath,
isRevalidation,
false
)
if (
mostSpecific !== null &&
mostSpecific !== fulfilled &&
mostSpecific.status === EntryStatus.Pending
) {
return mostSpecific
}
}
return fulfilled return fulfilled
} }
return getFromCacheMap( return getFromCacheMap(
......
import { cookies } from 'next/headers'
// A blocking route with a `generateStaticParams`-covered param. The page awaits
// `params` BEFORE reading `cookies()`. In the app-shell prefetch ('3') all
// params are withheld (app shells carry session data like cookies, but no
// params — not even static ones), so `await params` suspends here and the
// `cookies()` read is never reached — keeping the cookie value OUT of the app
// shell. (A cookie-only route with no preceding param access would instead
// include the cookie in the app shell, since cookies are allowed there — that
// would not be the blocking behavior we want to assert.)
//
// `cookies()` is still read outside any <Suspense>, so the route has no static
// shell and remains request-time blocking. It fails `next build`'s static-shell
// validation, which is why it lives in this dev-only fixture. Under instant()
// the cookie value must NOT commit while the lock is held; it only streams in
// after the lock releases.
export function generateStaticParams() {
return [{ id: 'x' }]
}
export default async function BlockingCookiesPage({
params,
}: {
params: Promise<{ id: string }>
}) {
await params
const cookieStore = await cookies()
const testCookie = cookieStore.get('testCookie')
return (
<div data-testid="blocking-cookie-value">
testCookie: {testCookie?.value ?? 'not set'}
</div>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1 data-testid="home-title">Instant Navigation API Test (blocking)</h1>
<ul>
<li>
<Link href="/blocking-cookies/x" id="link-to-blocking-cookies">
Go to blocking cookies page
</Link>
</li>
</ul>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
// Matches the `default` fixture: App Shells is implicit via
// `cacheComponents`, `prefetchInlining` stays `false`. This fixture holds
// routes with no static shell (a dynamic read outside any `<Suspense>`),
// which fail `next build`'s static-shell validation, so its suite runs in
// dev only and is never production-built.
exposeTestingApiInProductionBuild: true,
prefetchInlining: false,
},
}
module.exports = nextConfig
import { cookies } from 'next/headers'
// The deeper, blocking segment of the fallback route: reads request-time
// `cookies()` and has no <Suspense> of its own, so it has no static shell.
// Under instant() the navigation here must stay parked on the committed parent;
// the cookie value must not commit while the lock is held.
export default function ScopePage() {
return (
<div>
<h1 data-testid="blocking-scope-title">Scope</h1>
<Secret />
</div>
)
}
async function Secret() {
const cookieStore = await cookies()
return (
<div data-testid="blocking-secret">
testCookie: {cookieStore.get('testCookie')?.value ?? 'not set'}
</div>
)
}
import { ReactNode, Suspense } from 'react'
// `[lang]` is covered by generateStaticParams, so `/blocking-fallback/en` is a
// committed landing route. `[scope]` is not covered, so
// `/blocking-fallback/en/s1` is an on-demand fallback route. This layout owns
// the only <Suspense> boundary above that deeper segment, so its request-time
// work is held here rather than bailing the whole route.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function LangLayout({ children }: { children: ReactNode }) {
return (
<>
<p data-testid="blocking-parent">parent</p>
<Suspense fallback={<p data-testid="blocking-shell">shell</p>}>
{children}
</Suspense>
</>
)
}
import Link from 'next/link'
export default function LangHome() {
return (
<div>
<h1 data-testid="blocking-landing">Landing</h1>
<Link href="/blocking-fallback/en/s1" id="to-blocking-scope">
Go deeper
</Link>
</div>
)
}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
// Same shape as `cookies-page` (cookies read inside a <Suspense>), but the
// component awaits a `generateStaticParams`-covered `params` BEFORE reading
// `cookies()`. The app-shell prefetch withholds all params, so it suspends at
// `await params` and never reaches the cookie read — keeping the cookie value
// OUT of the instant shell. Contrast with `cookies-page`, where the cookie (a
// session value carried by the app shell) appears in the instant shell because
// nothing gates it.
export function generateStaticParams() {
return [{ id: 'x' }]
}
export default function CookiesWithParamPage({
params,
}: {
params: Promise<{ id: string }>
}) {
return (
<div>
<h1 data-testid="cookies-param-title">Cookies With Param Page</h1>
<Suspense
fallback={
<div data-testid="cookies-param-fallback">Loading cookies...</div>
}
>
<CookieContent params={params} />
</Suspense>
</div>
)
}
async function CookieContent({ params }: { params: Promise<{ id: string }> }) {
await params
const cookieStore = await cookies()
const testCookie = cookieStore.get('testCookie')
return (
<div data-testid="cookies-param-value">
testCookie: {testCookie?.value ?? 'not set'}
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
// A route that mixes a `generateStaticParams`-covered param (`lang`, resolved
// in the static shell by the parent layout) with an uncovered one (`slug`).
// The route opts into runtime prefetching, so `slug` is resolved by the runtime
// prefetch rather than the static shell. Under instant() we expect both to
// surface — `lang` from the static shell, `slug` from the runtime prefetch —
// while the genuinely request-time `connection()` sibling stays deferred until
// the lock releases.
export const instant: {
unstable_samples: Array<{ params: { lang: string; slug: string } }>
} = {
unstable_samples: [{ params: { lang: 'en', slug: 'anything' } }],
}
export const prefetch = 'allow-runtime'
export default function MixedParamsRuntimePage({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}) {
return (
<div>
<h1 data-testid="mixed-params-runtime-title">
Mixed Params Runtime Page
</h1>
<Suspense
fallback={<div data-testid="mixed-slug-fallback">Loading slug...</div>}
>
<SlugContent params={params} />
</Suspense>
<Suspense
fallback={
<div data-testid="mixed-dynamic-fallback">Loading dynamic...</div>
}
>
<DynamicContent />
</Suspense>
</div>
)
}
async function SlugContent({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}) {
const { slug } = await params
return <div data-testid="mixed-slug-value">slug: {slug}</div>
}
async function DynamicContent() {
await connection()
return <div data-testid="mixed-dynamic-value">dynamic content</div>
}
import { ReactNode } from 'react'
// `lang` IS covered by `generateStaticParams`, so it is part of the static
// shell. The layout awaits it OUTSIDE <Suspense>; under instant() the per-URL
// shell must resolve the covered `lang` here (not defer it), exactly like the
// build's prebuilt `en/[slug]` shell.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default async function MixedLangLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<>
<p data-testid="mixed-lang">lang: {lang}</p>
{children}
</>
)
}
...@@ -4,65 +4,132 @@ export default function HomePage() { ...@@ -4,65 +4,132 @@ export default function HomePage() {
return ( return (
<div> <div>
<h1 data-testid="home-title">Instant Navigation API Test</h1> <h1 data-testid="home-title">Instant Navigation API Test</h1>
<Link href="/target-page" id="link-to-target"> <ul>
Go to target page <li>
</Link> <Link href="/target-page" id="link-to-target">
<Link Go to target page
href="/runtime-prefetch-target?myParam=testValue" </Link>
id="link-to-runtime-prefetch" </li>
> <li>
Go to runtime prefetch target <Link
</Link> href="/runtime-prefetch-target?myParam=testValue"
<Link id="link-to-runtime-prefetch"
href="/full-prefetch-target" prefetch
prefetch={true} >
id="link-to-full-prefetch" Go to runtime prefetch target
> </Link>
Go to full prefetch target </li>
</Link> <li>
<Link href="/cookies-page" id="link-to-cookies-page"> <Link
Go to cookies page href="/full-prefetch-target"
</Link> prefetch={true}
<Link href="/dynamic-params/unknown" id="link-to-dynamic-params"> id="link-to-full-prefetch"
Go to dynamic params page >
</Link> Go to full prefetch target
<Link href="/dynamic-params/hello" id="link-to-static-dynamic-params"> </Link>
Go to static dynamic params page </li>
</Link> <li>
<Link href="/ungenerated-params/anything" id="link-to-ungenerated-params"> <Link href="/cookies-page" id="link-to-cookies-page">
Go to ungenerated params page Go to cookies page
</Link> </Link>
<Link </li>
href="/ungenerated-params-runtime/anything" <li>
id="link-to-ungenerated-params-runtime" <Link href="/cookies-with-param/x" id="link-to-cookies-with-param">
> Go to cookies-with-param page
Go to ungenerated params runtime page </Link>
</Link> </li>
<Link href="/search-params-page?foo=bar" id="link-to-search-params"> <li>
Go to search params page <Link href="/dynamic-params/unknown" id="link-to-dynamic-params">
</Link> Go to dynamic params page
{/* Plain anchor for MPA navigation testing (bypasses client-side routing) */} </Link>
<a href="/target-page" id="plain-link-to-target"> </li>
Go to target page (MPA) <li>
</a> <Link href="/dynamic-params/hello" id="link-to-static-dynamic-params">
<a href="/cookies-page" id="plain-link-to-cookies-page"> Go to static dynamic params page
Go to cookies page (MPA) </Link>
</a> </li>
<a href="/dynamic-params/unknown" id="plain-link-to-dynamic-params"> <li>
Go to dynamic params page (MPA) <Link
</a> href="/ungenerated-params/anything"
<a href="/dynamic-params/hello" id="plain-link-to-static-dynamic-params"> id="link-to-ungenerated-params"
Go to static dynamic params page (MPA) >
</a> Go to ungenerated params page
<a href="/search-params-page?foo=bar" id="plain-link-to-search-params"> </Link>
Go to search params page (MPA) </li>
</a> <li>
<Link href="/client-fetch-page" id="link-to-client-fetch"> <Link
Go to client fetch page href="/ungenerated-params-runtime/anything"
</Link> id="link-to-ungenerated-params-runtime"
<a href="/client-fetch-page" id="plain-link-to-client-fetch"> prefetch
Go to client fetch page (MPA) >
</a> Go to ungenerated params runtime page
</Link>
</li>
<li>
<Link
href="/mixed-params-runtime/en/anything"
id="link-to-mixed-params-runtime"
prefetch
>
Go to mixed params runtime page
</Link>
</li>
<li>
<Link
href="/mixed-params-runtime/en/anything"
id="link-to-mixed-params-runtime-no-prefetch"
>
Go to mixed params runtime page (no prefetch)
</Link>
</li>
<li>
<Link href="/search-params-page?foo=bar" id="link-to-search-params">
Go to search params page
</Link>
</li>
{/* Plain anchor for MPA navigation testing (bypasses client-side routing) */}
<li>
<a href="/target-page" id="plain-link-to-target">
Go to target page (MPA)
</a>
</li>
<li>
<a href="/cookies-page" id="plain-link-to-cookies-page">
Go to cookies page (MPA)
</a>
</li>
<li>
<a href="/dynamic-params/unknown" id="plain-link-to-dynamic-params">
Go to dynamic params page (MPA)
</a>
</li>
<li>
<a
href="/dynamic-params/hello"
id="plain-link-to-static-dynamic-params"
>
Go to static dynamic params page (MPA)
</a>
</li>
<li>
<a
href="/search-params-page?foo=bar"
id="plain-link-to-search-params"
>
Go to search params page (MPA)
</a>
</li>
<li>
<Link href="/client-fetch-page" id="link-to-client-fetch">
Go to client fetch page
</Link>
</li>
<li>
<a href="/client-fetch-page" id="plain-link-to-client-fetch">
Go to client fetch page (MPA)
</a>
</li>
</ul>
</div> </div>
) )
} }
...@@ -4,9 +4,9 @@ ...@@ -4,9 +4,9 @@
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: { experimental: {
// TODO(appShells): migrate this test to the two-phase (app shell + // App Shells is enabled implicitly by `cacheComponents`. `prefetchInlining`
// per-page data) prefetch behavior, then remove this override. See #94516. // is kept `false` so the non-inlined (speculative per-segment) static
appShells: false, // prefetch path is exercised alongside the app-shell prefetch.
// Enable the testing API in production builds for these tests // Enable the testing API in production builds for these tests
exposeTestingApiInProductionBuild: true, exposeTestingApiInProductionBuild: true,
prefetchInlining: false, prefetchInlining: false,
......
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