Unverified Commit c10b8959 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Remove `unstable_eager` (#97524)

The implementation of `unstable_eager` is currently incomplete, causes
bugs in the main Partial Prefetching flow (see #97469), and is generally
not worth the complexity it adds, so we're removing it. We may add
something like this back later if we think it's useful.

Importantly, removing it fixes a bug that caused apps that use
incremental opt-in (i.e. no global `partialPrefetching` config and
`export const prefetch = 'partial'`) to issue speculative prefetches for
all links without `prefetch={true}`, because any segment without an
explicit `prefetch = "partial"` was marked as needing eager prefetching,
which was then propagated to the whole route. See #97469 for a full
explanation.

This fix causes a lot of changes in tests, which were previously
incorrectly asserting that we should be seeing two requests. Now that
the unnecesary speculative prefetch is gone, most of them only see one.
parent 6fbd61c1
...@@ -577,7 +577,7 @@ For opted-out segments, the navigation blocks on the server. If the content depe ...@@ -577,7 +577,7 @@ For opted-out segments, the navigation blocks on the server. If the content depe
## Next steps ## Next steps
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and the migration path off `unstable_eager` - [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and a step-by-step adoption path
- [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration - [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration
- [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and should resolve before navigation - [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and should resolve before navigation
- [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering
......
...@@ -36,16 +36,11 @@ const InstantConfigSchema = z.union([ ...@@ -36,16 +36,11 @@ const InstantConfigSchema = z.union([
z.literal(false), z.literal(false),
]) ])
const PrefetchSchema = z.enum([ const PrefetchSchema = z.enum(['auto', 'partial', 'force-disabled'])
'auto',
'partial',
'unstable_eager',
'force-disabled',
])
export type Instant = InstantConfig | true | false export type Instant = InstantConfig | true | false
export type Prefetch = 'auto' | 'partial' | 'unstable_eager' | 'force-disabled' export type Prefetch = 'auto' | 'partial' | 'force-disabled'
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericInstantConfig type is used to avoid type widening issues with // the __GenericInstantConfig type is used to avoid type widening issues with
...@@ -138,9 +133,6 @@ const AppSegmentConfigSchema = z.object({ ...@@ -138,9 +133,6 @@ const AppSegmentConfigSchema = z.object({
* - 'partial' enables Partial Prefetching. Only Cache Components are * - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones. When a static prefetch is insufficient, * prefetched, not dynamic ones. When a static prefetch is insufficient,
* the segment may be prefetched with a runtime request instead. * the segment may be prefetched with a runtime request instead.
* - 'unstable_eager' behaves like 'partial' but, when App Shells are enabled,
* keeps eagerly prefetching the route's segments instead of relying on the
* shared app shell. Internal migration aid; not part of the public API.
* - 'force-disabled' disables prefetching for the segment. * - 'force-disabled' disables prefetching for the segment.
*/ */
prefetch: PrefetchSchema.optional(), prefetch: PrefetchSchema.optional(),
...@@ -197,7 +189,7 @@ export function parseAppSegmentConfig( ...@@ -197,7 +189,7 @@ export function parseAppSegmentConfig(
} }
case 'prefetch': { case 'prefetch': {
return { return {
message: `Invalid prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", "unstable_eager", or "force-disabled".`, message: `Invalid prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", or "force-disabled".`,
} }
} }
case 'unstable_dynamicStaleTime': { case 'unstable_dynamicStaleTime': {
...@@ -265,9 +257,6 @@ export type AppSegmentConfig = { ...@@ -265,9 +257,6 @@ export type AppSegmentConfig = {
* - 'partial' enables Partial Prefetching. Only Cache Components are * - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones. When a static prefetch is insufficient, * prefetched, not dynamic ones. When a static prefetch is insufficient,
* the segment may be prefetched with a runtime request instead. * the segment may be prefetched with a runtime request instead.
* - 'unstable_eager' behaves like 'partial' but, when App Shells are enabled,
* keeps eagerly prefetching the route's segments instead of relying on the
* shared app shell. Internal migration aid; not part of the public API.
* - 'force-disabled' disables prefetching for the segment. * - 'force-disabled' disables prefetching for the segment.
*/ */
prefetch?: Prefetch prefetch?: Prefetch
......
...@@ -25,10 +25,10 @@ import { ...@@ -25,10 +25,10 @@ import {
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers' import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue' import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
import { subtreeHasSpeculativePrefetch } from './scheduler' import { needsSpeculativePrefetch } from './scheduler'
import type { SegmentCacheEntry } from './cache' import type { SegmentCacheEntry } from './cache'
import { createCacheMap, type CacheMap } from './cache-map' import { createCacheMap, type CacheMap } from './cache-map'
import type { FetchStrategy } from './types' import type { PrefetchTaskFetchStrategy } from './types'
type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa' type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'
...@@ -535,19 +535,19 @@ export function getCurrentNavigationGate(): Promise<void> | null { ...@@ -535,19 +535,19 @@ export function getCurrentNavigationGate(): Promise<void> | null {
* enabled for the target route, and no whole-route ("speculative") prefetch * enabled for the target route, and no whole-route ("speculative") prefetch
* would have been made, only the shell is prefetched — so that's all a * would have been made, only the shell is prefetched — so that's all a
* navigation should be allowed to match. A speculative prefetch happens for a * navigation should be allowed to match. A speculative prefetch happens for a
* `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the * `<Link prefetch={true}>`, in which case the concrete-param entry is genuinely
* concrete-param entry is genuinely warm and may be matched. * warm and may be matched.
* *
* Always returns false outside the testing API, via the aliased * Always returns false outside the testing API, via the aliased
* `navigation-testing-lock.disabled` module. * `navigation-testing-lock.disabled` module.
*/ */
export function shouldRestrictNavigationToShell( export function shouldRestrictNavigationToShell(
rootPrefetchHints: number, rootPrefetchHints: number,
linkFetchStrategy: FetchStrategy linkFetchStrategy: PrefetchTaskFetchStrategy
): boolean { ): boolean {
return ( return (
isNavigationLocked() && isNavigationLocked() &&
(rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 && (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&
!subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints) !needsSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)
) )
} }
...@@ -624,8 +624,7 @@ function processQueueInMicrotask() { ...@@ -624,8 +624,7 @@ function processQueueInMicrotask() {
// Finished prefetching the route tree. The two-phase (Shell then // Finished prefetching the route tree. The two-phase (Shell then
// Speculative) flow only applies to routes that have opted into // Speculative) flow only applies to routes that have opted into
// Partial Prefetching — either globally via the `partialPrefetching` // Partial Prefetching — either globally via the `partialPrefetching`
// config or per segment (`prefetch: 'partial'` or // config or per segment (`prefetch: 'partial'`), both surfaced as the
// `'unstable_eager'`), all surfaced as the
// `SubtreeHasPartialPrefetching` hint on the route tree. Every other // `SubtreeHasPartialPrefetching` hint on the route tree. Every other
// route skips the Shell phase and goes straight to Speculative. // route skips the Shell phase and goes straight to Speculative.
// //
...@@ -907,16 +906,14 @@ function pingRootRouteTree( ...@@ -907,16 +906,14 @@ function pingRootRouteTree(
? FetchStrategy.StaticShell ? FetchStrategy.StaticShell
: FetchStrategy.PPR : FetchStrategy.PPR
// In PPF, links may skip speculative prefetching if they only need a shell.
if ( if (
staticWalkStrategy === FetchStrategy.PPR && staticWalkStrategy === FetchStrategy.PPR &&
!subtreeHasSpeculativePrefetch( !needsSpeculativePrefetch(
task.fetchStrategy, task.fetchStrategy,
tree.prefetchHints route.tree.prefetchHints
) )
) { ) {
// Nothing in the target route needs to be speculatively prefetched.
// Bail out. (A PPR walk is the Speculative pass; same check as
// the per-subtree bail in pingNewPartOfCacheComponentsTree.)
return PrefetchTaskExitStatus.Done return PrefetchTaskExitStatus.Done
} }
...@@ -1172,17 +1169,11 @@ function pingStaticHead( ...@@ -1172,17 +1169,11 @@ function pingStaticHead(
* walks prefetch static data and partial entries are acceptable — the * walks prefetch static data and partial entries are acceptable — the
* dynamic holes are filled by the navigation-time request. * dynamic holes are filled by the navigation-time request.
* *
* Note that on a Partial Prefetching route, non-eager subtrees are still * Note: The runtime contract is affordable because most
* skipped by the Speculative pass of a default (auto) link — eagerness is
* unaffected by this predicate. But every segment the pass DOES walk (eager
* segments, and everything on a `prefetch={true}` walk) is held to the
* runtime-completeness contract. The contract is affordable because most
* routes carry the ShouldAttemptStaticPrefetch hint: their segments are * routes carry the ShouldAttemptStaticPrefetch hint: their segments are
* prefetched statically and the responses' own sufficiency signal makes a * prefetched statically and the responses' own sufficiency signal makes a
* runtime request rare. On a hint-unset route, a walked segment deopts * runtime request rare. On a hint-unset route, a walked segment deopts
* directly to the batched runtime request — which then serves the segment's * directly to the batched runtime request.
* whole subtree, so navigations into it are complete without a
* navigation-time request.
* *
* This is also the gate for the batched runtime request at the end of * This is also the gate for the batched runtime request at the end of
* pingRootRouteTree; requiring runtime completeness does not itself mean a * pingRootRouteTree; requiring runtime completeness does not itself mean a
...@@ -1479,15 +1470,11 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1479,15 +1470,11 @@ function pingNewPartOfCacheComponentsTree(
// runtime data carries it, and the dynamic holes are filled by the // runtime data carries it, and the dynamic holes are filled by the
// navigation-time request. // navigation-time request.
// In PPF, links may skip speculative prefetching if they only need a shell.
if ( if (
// Only the Speculative pass skips subtrees with nothing to speculatively
// prefetch. (It's also the only pass that walks at FetchStrategy.PPR;
// the Shell phase walks at StaticShell and covers the whole new tree.)
fetchStrategy === FetchStrategy.PPR && fetchStrategy === FetchStrategy.PPR &&
!subtreeHasSpeculativePrefetch(task.fetchStrategy, tree.prefetchHints) !needsSpeculativePrefetch(task.fetchStrategy, route.tree.prefetchHints)
) { ) {
// Nothing in the new part of the tree needs to be speculatively prefetched.
// Bail out.
return PrefetchTaskExitStatus.Done return PrefetchTaskExitStatus.Done
} }
...@@ -2678,24 +2665,21 @@ function doesCurrentSegmentMatchCachedSegment( ...@@ -2678,24 +2665,21 @@ function doesCurrentSegmentMatchCachedSegment(
} }
/** /**
* Decides whether to skip the speculative prefetch of a subtree. Usually we * Decides whether to speculatively prefetch a subtree. Under Partial
* only perform a speculative prefetch if the Link's prefetch prop is set to * Prefetching we only do this if the Link's prefetch prop is set to true —
* true. However, we also will do a speculative prefetch if the prefetching * otherwise the subtree relies on the shell that the Shell phase prefetches.
* mode of the segment is set to "unstable_eager".
*/ */
export function subtreeHasSpeculativePrefetch( export function needsSpeculativePrefetch(
fetchStrategy: FetchStrategy, taskfetchStrategy: PrefetchTaskFetchStrategy,
prefetchHints: number rootPrefetchHints: number
): boolean { ): boolean {
return ( if ((rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0) {
// Check if this is a "full" prefetch (<Link prefetch={true}>). // PPF - only needs a speculative prefetch if this is a `<Link prefetch={true}>`.
fetchStrategy === FetchStrategy.Full || return taskfetchStrategy === FetchStrategy.Full
// Check if something in this subtree is configured to be eagerly } else {
// prefetched at the route level. Segments that don't opt into Partial // non-PPF -- all prefetches are speculative.
// Prefetching are marked eager, so a route without any Partial Prefetching return true
// still speculatively prefetches everything. }
(prefetchHints & PrefetchHint.SubtreeHasEagerPrefetch) !== 0
)
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -1099,7 +1099,7 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1099,7 +1099,7 @@ async function generateStagedDynamicFlightRenderResultNode(
// Check if this route should runtime-cache its navigation. This happens when // Check if this route should runtime-cache its navigation. This happens when
// Partial Prefetching is enabled for the route, either per segment (a // Partial Prefetching is enabled for the route, either per segment (a
// `prefetch` of 'partial' or 'unstable_eager') or globally (the // `prefetch` of 'partial') or globally (the
// `partialPrefetching` config). If so, we piggyback on the dynamic render to // `partialPrefetching` config). If so, we piggyback on the dynamic render to
// fill caches and then spawn a final runtime prerender whose result stream // fill caches and then spawn a final runtime prerender whose result stream
// is embedded in the RSC payload. This is gated because it adds extra server // is embedded in the RSC payload. This is gated because it adds extra server
...@@ -1464,7 +1464,6 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1464,7 +1464,6 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
prefetchStage = RenderStage.Static prefetchStage = RenderStage.Static
} else { } else {
if (prefetchMode === PrefetchingMode.Partial) { if (prefetchMode === PrefetchingMode.Partial) {
// TODO(app-shells): model `partialPrefetching: "unstable_eager"`
// TODO(app-shells): if this navigation came from <Link prefetch={true} />, // TODO(app-shells): if this navigation came from <Link prefetch={true} />,
// we should show the shell for a speculative prefetch // we should show the shell for a speculative prefetch
// (which can have more data than the app shell) // (which can have more data than the app shell)
...@@ -2363,7 +2362,7 @@ async function getErrorRSCPayload( ...@@ -2363,7 +2362,7 @@ async function getErrorRSCPayload(
errorHints, errorHints,
errorPrefetchInliningEnabled, errorPrefetchInliningEnabled,
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
ctx.renderOpts.partialPrefetching, Boolean(ctx.renderOpts.partialPrefetching),
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -3848,7 +3847,7 @@ async function renderToStream( ...@@ -3848,7 +3847,7 @@ async function renderToStream(
// embedded in the initial RSC payload so the client can cache // embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration. This is enabled when // runtime-prefetchable content during hydration. This is enabled when
// Partial Prefetching is on for the route, either per segment (a // Partial Prefetching is on for the route, either per segment (a
// `prefetch` of 'partial' or 'unstable_eager') or globally (the // `prefetch` of 'partial') or globally (the
// `partialPrefetching` config). // `partialPrefetching` config).
if ( if (
Boolean(renderOpts.partialPrefetching) || Boolean(renderOpts.partialPrefetching) ||
...@@ -5288,7 +5287,6 @@ async function getPrefetchingModeForPage( ...@@ -5288,7 +5287,6 @@ async function getPrefetchingModeForPage(
const debug = const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
// TODO(app-shells): support "unstable_eager"
if (renderOpts.partialPrefetching) { if (renderOpts.partialPrefetching) {
debug?.('using prefetching mode Partial because of next.config.js') debug?.('using prefetching mode Partial because of next.config.js')
return PrefetchingMode.Partial return PrefetchingMode.Partial
...@@ -5399,7 +5397,7 @@ type StreamRevealStage = ...@@ -5399,7 +5397,7 @@ type StreamRevealStage =
| RenderStage.Runtime | RenderStage.Runtime
function navigationHasAppShell(navigationKind: DevNavigationKind): boolean { function navigationHasAppShell(navigationKind: DevNavigationKind): boolean {
// TODO(app-shells): when we implement `<Link prefetch={true}>/`prefetch = "unstable_eager"` in dev, // TODO(app-shells): when we implement `<Link prefetch={true}>` in dev,
// this might need to be adjusted, because we'll use `Runtime` for the stage // this might need to be adjusted, because we'll use `Runtime` for the stage
return ( return (
navigationKind.type === 'prefetched-client' && navigationKind.type === 'prefetched-client' &&
......
...@@ -191,7 +191,7 @@ async function createComponentTreeInternal( ...@@ -191,7 +191,7 @@ async function createComponentTreeInternal(
parseLoaderTree(tree) parseLoaderTree(tree)
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining) const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const partialPrefetching = ctx.renderOpts.partialPrefetching const partialPrefetching = Boolean(ctx.renderOpts.partialPrefetching)
const { const {
layout, layout,
......
...@@ -61,7 +61,7 @@ export async function computeSegmentPrefetchHints( ...@@ -61,7 +61,7 @@ export async function computeSegmentPrefetchHints(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined, partialPrefetching: boolean,
// Whether this segment is at or above the root layout (no layout was found // Whether this segment is at or above the root layout (no layout was found
// above it). // above it).
isRootLayoutOrAbove: boolean isRootLayoutOrAbove: boolean
...@@ -76,11 +76,7 @@ export async function computeSegmentPrefetchHints( ...@@ -76,11 +76,7 @@ export async function computeSegmentPrefetchHints(
const instantConfig = mod ? (mod as AppSegmentConfig).instant : undefined const instantConfig = mod ? (mod as AppSegmentConfig).instant : undefined
const prefetchConfig = const prefetchConfig =
(mod ? (mod as AppSegmentConfig).prefetch : undefined) ?? (mod ? (mod as AppSegmentConfig).prefetch : undefined) ??
(partialPrefetching === 'unstable_eager' (partialPrefetching ? 'partial' : undefined)
? 'unstable_eager'
: partialPrefetching
? 'partial'
: undefined)
let prefetchHints = 0 let prefetchHints = 0
// Union in the precomputed build-time hints (e.g. segment inlining // Union in the precomputed build-time hints (e.g. segment inlining
...@@ -132,25 +128,10 @@ export async function computeSegmentPrefetchHints( ...@@ -132,25 +128,10 @@ export async function computeSegmentPrefetchHints(
if (prefetchConfig === 'partial') { if (prefetchConfig === 'partial') {
prefetchHints |= PrefetchHint.SubtreeHasPartialPrefetching prefetchHints |= PrefetchHint.SubtreeHasPartialPrefetching
} else if (prefetchConfig === 'unstable_eager') {
// Like 'partial' (uses the PPR fetch strategy) but also marks the segment
// as eager, so App Shells keeps prefetching it instead of relying on the
// shared app shell.
prefetchHints |=
PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasEagerPrefetch
} else if (prefetchConfig === 'force-disabled') { } else if (prefetchConfig === 'force-disabled') {
prefetchHints |= PrefetchHint.PrefetchDisabled prefetchHints |= PrefetchHint.PrefetchDisabled
} }
// Mark the segment as "eager" unless its effective prefetch strategy is
// 'partial'. 'unstable_eager' already set the bit above. Under App Shells,
// a subtree with no eager segment skips its Speculative prefetch and relies
// on the shared app shell instead.
if (prefetchConfig !== 'partial') {
prefetchHints |= PrefetchHint.SubtreeHasEagerPrefetch
}
// Check if this segment has a loading boundary // Check if this segment has a loading boundary
if (loading) { if (loading) {
prefetchHints |= PrefetchHint.SegmentHasLoadingBoundary prefetchHints |= PrefetchHint.SegmentHasLoadingBoundary
...@@ -176,7 +157,7 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -176,7 +157,7 @@ async function createTransportTreeFromLoaderTreeImpl(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
didFindRootLayout: boolean didFindRootLayout: boolean
...@@ -254,7 +235,7 @@ export async function createTransportTreeFromLoaderTree( ...@@ -254,7 +235,7 @@ export async function createTransportTreeFromLoaderTree(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
// Whether a root layout was already found above this loader tree slice, so a // Whether a root layout was already found above this loader tree slice, so a
...@@ -285,7 +266,7 @@ export async function createFullTransportTreeFromLoaderTree( ...@@ -285,7 +266,7 @@ export async function createFullTransportTreeFromLoaderTree(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any searchParams: any
): Promise<FullTransportNode> { ): Promise<FullTransportNode> {
...@@ -314,7 +295,7 @@ export async function createRouteTreePrefetch( ...@@ -314,7 +295,7 @@ export async function createRouteTreePrefetch(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
// See note on createTransportTreeFromLoaderTree's didFindRootLayout. // See note on createTransportTreeFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false didFindRootLayout: boolean = false
......
...@@ -51,10 +51,9 @@ export function isFrameworkErrorRoute(route: string | undefined): boolean { ...@@ -51,10 +51,9 @@ export function isFrameworkErrorRoute(route: string | undefined): boolean {
} }
/** /**
* Matches any `prefetch` config that enables Partial Prefetching for the * Matches the `prefetch` config that enables Partial Prefetching for the
* segment: 'partial' or 'unstable_eager'. A route with Partial Prefetching * segment: 'partial'. A route with Partial Prefetching enabled also
* enabled also runtime-caches its navigations, so this gates the runtime * runtime-caches its navigations, so this gates the runtime prefetch spawn.
* prefetch spawn.
*/ */
export async function anySegmentHasPartialPrefetchingEnabled( export async function anySegmentHasPartialPrefetchingEnabled(
tree: LoaderTree tree: LoaderTree
...@@ -65,7 +64,7 @@ export async function anySegmentHasPartialPrefetchingEnabled( ...@@ -65,7 +64,7 @@ export async function anySegmentHasPartialPrefetchingEnabled(
const prefetchConfig = layoutOrPageMod const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch ? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined : undefined
if (prefetchConfig === 'partial' || prefetchConfig === 'unstable_eager') { if (prefetchConfig === 'partial') {
return true return true
} }
......
...@@ -81,7 +81,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -81,7 +81,7 @@ export async function walkTreeWithFlightRouterState({
parsedRequestHeaders, parsedRequestHeaders,
} = ctx } = ctx
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining) const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const partialPrefetching = ctx.renderOpts.partialPrefetching const partialPrefetching = Boolean(ctx.renderOpts.partialPrefetching)
const [segment, parallelRoutes, modules] = loaderTreeToFilter const [segment, parallelRoutes, modules] = loaderTreeToFilter
......
...@@ -805,9 +805,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -805,9 +805,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
pageExtensions: z.array(z.string()).min(1).optional(), pageExtensions: z.array(z.string()).min(1).optional(),
instrumentationClientInject: z.array(z.string()).optional(), instrumentationClientInject: z.array(z.string()).optional(),
partialPrefetching: z partialPrefetching: z.boolean().optional(),
.union([z.boolean(), z.literal('unstable_eager')])
.optional(),
poweredByHeader: z.boolean().optional(), poweredByHeader: z.boolean().optional(),
productionBrowserSourceMaps: z.boolean().optional(), productionBrowserSourceMaps: z.boolean().optional(),
reactCompiler: z.union([ reactCompiler: z.union([
......
...@@ -2015,12 +2015,8 @@ export interface NextConfig { ...@@ -2015,12 +2015,8 @@ export interface NextConfig {
* *
* When `false` or omitted, this does nothing (the legacy behavior, where * When `false` or omitted, this does nothing (the legacy behavior, where
* dynamic data is included in the prefetch). * dynamic data is included in the prefetch).
*
* `'unstable_eager'` is like `true`, except the default becomes
* `'unstable_eager'` instead of `'partial'`: every Link has an implied
* prefetch={true}. Internal migration aid; not part of the public API.
*/ */
partialPrefetching?: boolean | 'unstable_eager' partialPrefetching?: boolean
cacheLife?: { cacheLife?: {
[profile: string]: { [profile: string]: {
......
...@@ -68,16 +68,14 @@ export function logExperimentalInfo({ ...@@ -68,16 +68,14 @@ export function logExperimentalInfo({
}: { }: {
experimentalFeatures?: ConfiguredExperimentalFeature[] experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean cacheComponents?: boolean
partialPrefetching?: boolean | 'unstable_eager' partialPrefetching?: boolean
}) { }) {
if (cacheComponents) { if (cacheComponents) {
Log.bootstrap(`- Cache Components enabled`) Log.bootstrap(`- Cache Components enabled`)
} }
if (partialPrefetching) { if (partialPrefetching) {
const mode = Log.bootstrap(`- Partial Prefetching enabled`)
partialPrefetching === 'unstable_eager' ? ' (unstable_eager)' : ''
Log.bootstrap(`- Partial Prefetching enabled${mode}`)
} }
if (experimentalFeatures?.length) { if (experimentalFeatures?.length) {
......
...@@ -22,8 +22,8 @@ export type ServerInitResult = { ...@@ -22,8 +22,8 @@ export type ServerInitResult = {
experimentalFeatures: ConfiguredExperimentalFeature[] experimentalFeatures: ConfiguredExperimentalFeature[]
// Whether cache components is enabled // Whether cache components is enabled
cacheComponents: boolean cacheComponents: boolean
// Whether partial prefetching is enabled (and its mode) // Whether partial prefetching is enabled
partialPrefetching?: boolean | 'unstable_eager' partialPrefetching?: boolean
// Whether AGENTS.md / CLAUDE.md auto-generation is enabled (default true) // Whether AGENTS.md / CLAUDE.md auto-generation is enabled (default true)
agentRules?: boolean agentRules?: boolean
// Whether the development server memory threshold restart is enabled // Whether the development server memory threshold restart is enabled
...@@ -107,7 +107,7 @@ async function initializeImpl(opts: { ...@@ -107,7 +107,7 @@ async function initializeImpl(opts: {
distDir: string distDir: string
experimentalFeatures: ConfiguredExperimentalFeature[] experimentalFeatures: ConfiguredExperimentalFeature[]
cacheComponents: boolean cacheComponents: boolean
partialPrefetching?: boolean | 'unstable_eager' partialPrefetching?: boolean
devMemoryThresholdRestart: boolean devMemoryThresholdRestart: boolean
}): Promise<ServerInitResult> { }): Promise<ServerInitResult> {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER const type = process.env.__NEXT_PRIVATE_RENDER_WORKER
......
...@@ -159,16 +159,11 @@ const API_DOCS: Record< ...@@ -159,16 +159,11 @@ const API_DOCS: Record<
prefetch: { prefetch: {
description: `Controls prefetching behavior for this segment. Some options are experimental and may change.`, description: `Controls prefetching behavior for this segment. Some options are experimental and may change.`,
link: '(docs coming soon)', link: '(docs coming soon)',
type: `"auto" | "partial" | "unstable_eager" | "force-disabled"`, type: `"auto" | "partial" | "force-disabled"`,
options: { options: {
auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.', auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.',
partial: partial:
'Enables Partial Prefetching for this segment. When a static prefetch is insufficient, Next.js may prefetch the segment with a runtime server request so it can access session data, such as cookies.', 'Enables Partial Prefetching for this segment. When a static prefetch is insufficient, Next.js may prefetch the segment with a runtime server request so it can access session data, such as cookies.',
unstable_eager:
'Like "partial", but adds an implied prop of prefetch={true} to ' +
'every Link. This option only exists to aid migration of apps that ' +
'adopted Partial Prefetching in canary before the behavior changed to ' +
'only fetch the shell by default.',
'force-disabled': 'Never prefetch this segment.', 'force-disabled': 'Never prefetch this segment.',
}, },
insertText: `prefetch = 'partial';`, insertText: `prefetch = 'partial';`,
......
...@@ -189,9 +189,9 @@ export const enum PrefetchHint { ...@@ -189,9 +189,9 @@ export const enum PrefetchHint {
// This segment or one of its descendants opts into Partial Prefetching, i.e. // This segment or one of its descendants opts into Partial Prefetching, i.e.
// uses the two-phase (Shell then Speculative) prefetch flow. Set when // uses the two-phase (Shell then Speculative) prefetch flow. Set when
// `prefetch` is 'partial' or 'unstable_eager' (including the defaults // `prefetch` is 'partial' (including the default implied by the global
// implied by the global `partialPrefetching` config). Propagates upward so // `partialPrefetching` config). Propagates upward so the root segment
// the root segment reflects the entire subtree. // reflects the entire subtree.
// //
// Partial Prefetching segments require RUNTIME COMPLETENESS: a prefetch // Partial Prefetching segments require RUNTIME COMPLETENESS: a prefetch
// isn't considered done for such a segment until an entry at least as // isn't considered done for such a segment until an entry at least as
...@@ -246,12 +246,10 @@ export const enum PrefetchHint { ...@@ -246,12 +246,10 @@ export const enum PrefetchHint {
// (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse // (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse
// it without considering caches populated by older builds. // it without considering caches populated by older builds.
// This segment or one of its descendants prefetches "eagerly" — i.e. its // NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch
// effective prefetch strategy is anything other than 'partial'. Used by // (prefetch: 'unstable_eager', plus every segment that did not opt into
// the scheduler's phasing: a non-eager subtree relies on the shell the // Partial Prefetching). After `unstable_eager` was removed, it's no longer needed.
// Shell phase prefetches and skips its Speculative prefetch. Propagates
// upward so the root reflects the entire subtree.
SubtreeHasEagerPrefetch = 0b1000000000000,
// This segment or one of its descendants exports `instant = false`, // This segment or one of its descendants exports `instant = false`,
// explicitly opting out of Partial Prefetching. Propagates upward so the root // explicitly opting out of Partial Prefetching. Propagates upward so the root
// reflects the entire subtree. Used only to suppress the dev-time // reflects the entire subtree. Used only to suppress the dev-time
...@@ -311,8 +309,7 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled ...@@ -311,8 +309,7 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const SubtreePrefetchHints = export const SubtreePrefetchHints =
PrefetchHint.SubtreeHasPartialPrefetching | PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasLoadingBoundary | PrefetchHint.SubtreeHasLoadingBoundary |
PrefetchHint.SubtreeHasInstantFalse | PrefetchHint.SubtreeHasInstantFalse
PrefetchHint.SubtreeHasEagerPrefetch
/** /**
* Folds a child segment's prefetch hints into its parent's, propagating the * Folds a child segment's prefetch hints into its parent's, propagating the
...@@ -342,13 +339,8 @@ export function propagateSubtreeBits( ...@@ -342,13 +339,8 @@ export function propagateSubtreeBits(
) { ) {
parentHints |= PrefetchHint.SubtreeHasLoadingBoundary parentHints |= PrefetchHint.SubtreeHasLoadingBoundary
} }
// And for eager prefetch. The bit is set directly on each eager segment, so // And for `instant = false`. The bit is set directly on each opted-out
// there's no separate segment-local flag — propagate it as-is. // segment, so there's no separate segment-local flag — propagate it as-is.
if (childHints & PrefetchHint.SubtreeHasEagerPrefetch) {
parentHints |= PrefetchHint.SubtreeHasEagerPrefetch
}
// And for `instant = false`. Like eager prefetch, the bit is set directly on
// each opted-out segment, so propagate it as-is.
if (childHints & PrefetchHint.SubtreeHasInstantFalse) { if (childHints & PrefetchHint.SubtreeHasInstantFalse) {
parentHints |= PrefetchHint.SubtreeHasInstantFalse parentHints |= PrefetchHint.SubtreeHasInstantFalse
} }
......
...@@ -991,11 +991,11 @@ describe('cached navigations', () => { ...@@ -991,11 +991,11 @@ describe('cached navigations', () => {
}) })
}) })
// A `prefetch` config that enables Partial Prefetching ('partial' or // A `prefetch` config that enables Partial Prefetching ('partial') also opts
// 'unstable_eager') also opts the route into runtime Cached Navigations, // the route into runtime Cached Navigations, even though this fixture does
// even though this fixture does not set the global `partialPrefetching` // not set the global `partialPrefetching` flag. Contrast with
// flag. Contrast with `partially-static`, which has no `prefetch` config // `partially-static`, which has no `prefetch` config and only gets static
// and only gets static caching. // caching.
async function expectRuntimeCachedOnSecondNavigation(route: string) { async function expectRuntimeCachedOnSecondNavigation(route: string) {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
...@@ -1057,8 +1057,4 @@ describe('cached navigations', () => { ...@@ -1057,8 +1057,4 @@ describe('cached navigations', () => {
it('runtime-caches a route with prefetch = "partial"', async () => { it('runtime-caches a route with prefetch = "partial"', async () => {
await expectRuntimeCachedOnSecondNavigation('/prefetch-partial') await expectRuntimeCachedOnSecondNavigation('/prefetch-partial')
}) })
it('runtime-caches a route with prefetch = "unstable_eager"', async () => {
await expectRuntimeCachedOnSecondNavigation('/prefetch-eager')
})
}) })
...@@ -38,11 +38,6 @@ export default function Home() { ...@@ -38,11 +38,6 @@ export default function Home() {
Go to prefetch=partial page Go to prefetch=partial page
</Link> </Link>
</li> </li>
<li>
<Link href="/prefetch-eager" prefetch={false}>
Go to prefetch=unstable_eager page
</Link>
</li>
</ul> </ul>
</main> </main>
) )
......
import { RuntimeContent } from '../../components/runtime-content'
// `prefetch = 'unstable_eager'` enables Partial Prefetching, which also opts
// the route into runtime Cached Navigations.
export const prefetch = 'unstable_eager'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return <RuntimeContent searchParams={searchParams} />
}
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/posts/1">Post 1 (default)</LinkAccordion>
</li>
<li>
<LinkAccordion href="/posts/2">Post 2 (default)</LinkAccordion>
</li>
</ul>
</main>
)
}
import { Suspense } from 'react'
type Params = { id: string }
// No per-segment `prefetch`. The route's prefetch config comes from
// the global `partialPrefetching: 'unstable_eager'` in next.config, which makes
// it eager — so the App Shells skip does NOT apply.
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p id="shell">App shell</p>}>
<ParamContent params={params} />
</Suspense>
</main>
)
}
async function ParamContent({ params }: { params: Promise<Params> }) {
const { id } = await params
return <p id="param-value">{`Eager post ${id}`}</p>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Opt the whole app into Partial Prefetching in "eager" mode. Every route's
// default prefetch config becomes 'unstable_eager', so under App Shells the
// per-link Speculative prefetch is NOT skipped — even for routes with no
// per-segment `prefetch` export.
partialPrefetching: 'unstable_eager',
experimental: {
prefetchInlining: true,
optimisticRouting: true,
cachedNavigations: true,
varyParams: true,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('App Shell prefetching - global unstable_eager', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('does NOT skip the Speculative prefetch when partialPrefetching is "unstable_eager" globally', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// /posts/[id] has no per-segment prefetch config, but the global
// `partialPrefetching: 'unstable_eager'` makes it eager. Reveal /posts/1 to
// prime the shared app shell.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/posts/1"]')
.click()
})
// Reveal /posts/2 — a different param, shell already cached. Because the
// global config makes the route eager, the per-link Speculative prefetch
// still fires for param 2 (a single request carrying "Eager post 2"),
// rather than firing no requests as a non-eager route's second link would.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/posts/2"]')
.click()
},
{ includes: 'Eager post 2' }
)
})
})
import { Suspense } from 'react'
type Params = { id: string }
// Combines both segment-level opt-ins: `instant` (which on its own
// behaves like 'partial' — not eager) AND `prefetch = 'unstable_eager'`.
// 'unstable_eager' wins: the segment is marked eager, so under App Shells the
// per-link Speculative prefetch still fires and the param-specific content
// below IS prefetched.
export const instant = true
export const prefetch = 'unstable_eager'
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
{/* The fallback is the param-independent app shell. */}
<Suspense fallback={<p id="shell">Eager-instant app shell</p>}>
<ParamContent params={params} />
</Suspense>
</main>
)
}
async function ParamContent({ params }: { params: Promise<Params> }) {
const { id } = await params
return <p id="param-value">{`Eager-instant post ${id}`}</p>
}
import { Suspense } from 'react'
type Params = { id: string }
// Opts into Partial Prefetching in "eager" mode. Behaves like 'partial', but
// under App Shells it keeps prefetching the route's segments instead of relying
// on the shared app shell — so the param-specific content below IS prefetched.
export const prefetch = 'unstable_eager'
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
{/* The fallback is the param-independent app shell. */}
<Suspense fallback={<p id="shell">Eager app shell</p>}>
<ParamContent params={params} />
</Suspense>
</main>
)
}
async function ParamContent({ params }: { params: Promise<Params> }) {
const { id } = await params
return <p id="param-value">{`Eager post ${id}`}</p>
}
...@@ -108,26 +108,6 @@ export default function Page() { ...@@ -108,26 +108,6 @@ export default function Page() {
</li> </li>
</ul> </ul>
<h2>Eager posts</h2>
<ul>
<li>
<LinkAccordion href="/eager/1">Eager 1 (default)</LinkAccordion>
</li>
<li>
<LinkAccordion href="/eager/2">Eager 2 (default)</LinkAccordion>
</li>
<li>
<LinkAccordion href="/eager-instant/1">
Eager-instant 1 (instant + unstable_eager)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/eager-instant/2">
Eager-instant 2 (instant + unstable_eager)
</LinkAccordion>
</li>
</ul>
<h2>Complete shell</h2> <h2>Complete shell</h2>
<ul> <ul>
<li> <li>
......
...@@ -30,7 +30,7 @@ export default async function Page({ ...@@ -30,7 +30,7 @@ export default async function Page({
return ( return (
<div> <div>
<p id="page-independent-head">Independent head page</p> <p id="page-independent-head">Independent head page</p>
<LinkAccordion href={`/test-independent-head/${sibling}`}> <LinkAccordion href={`/test-independent-head/${sibling}`} prefetch={true}>
Go to {sibling} Go to {sibling}
</LinkAccordion> </LinkAccordion>
</div> </div>
......
...@@ -644,7 +644,7 @@ describe('prefetch inlining', () => { ...@@ -644,7 +644,7 @@ describe('prefetch inlining', () => {
// route's static-attempt hint is unset because the page reads cookies, // route's static-attempt hint is unset because the page reads cookies,
// so the walked layout deopts directly to the batched runtime shell, // so the walked layout deopts directly to the batched runtime shell,
// which serves its whole subtree. The inlined layout content arrives in // which serves its whole subtree. The inlined layout content arrives in
// that runtime response. (No static bundle request fires: the Shell // that runtime shell response. (No static bundle request fires: the Shell
// phase already runtime-cached every entry in the bundle chain, and a // phase already runtime-cached every entry in the bundle chain, and a
// runtime-complete entry is never re-fetched by a static prefetch.) // runtime-complete entry is never re-fetched by a static prefetch.)
await act( await act(
...@@ -720,7 +720,7 @@ describe('prefetch inlining', () => { ...@@ -720,7 +720,7 @@ describe('prefetch inlining', () => {
}, },
// The layout reads cookies, so the route's static-attempt hint is // The layout reads cookies, so the route's static-attempt hint is
// unset and the Speculative pass deopts the layout directly to the // unset and the Speculative pass deopts the layout directly to the
// batched runtime prefetch, which serves the whole subtree — the // batched runtime shell, which serves the whole subtree — the
// static inner layout and page ride along in that single runtime // static inner layout and page ride along in that single runtime
// response. No static bundle request fires: every entry was already // response. No static bundle request fires: every entry was already
// runtime-cached at the shell tier by the Shell phase, and a // runtime-cached at the shell tier by the Shell phase, and a
...@@ -820,7 +820,7 @@ describe('prefetch inlining', () => { ...@@ -820,7 +820,7 @@ describe('prefetch inlining', () => {
.click() .click()
}, },
// Same as the runtime passthrough test: the hint-unset layout deopts // Same as the runtime passthrough test: the hint-unset layout deopts
// to the batched runtime prefetch, which serves the whole subtree // to the batched runtime shell, which serves the whole subtree
// (both slots) in a single runtime response. // (both slots) in a single runtime response.
{ includes: 'Runtime parallel main content', kind: 'runtime' } { includes: 'Runtime parallel main content', kind: 'runtime' }
) )
...@@ -842,8 +842,8 @@ describe('prefetch inlining', () => { ...@@ -842,8 +842,8 @@ describe('prefetch inlining', () => {
// [item] param and searchParams, making it depend on runtime data. // [item] param and searchParams, making it depend on runtime data.
// //
// Because the layout reads cookies, the route's static-attempt hint is // Because the layout reads cookies, the route's static-attempt hint is
// unset, so on this Partial Prefetching route every per-link prefetch // unset, so on this Partial Prefetching route every shell and prefetch
// deopts its new subtree to the batched runtime prefetch. The head is // deopt its new subtree to a runtime request. The head is
// param-dependent, so it is NOT part of the reusable App Shell — but // param-dependent, so it is NOT part of the reusable App Shell — but
// whenever a runtime prefetch fires for a segment, the head rides // whenever a runtime prefetch fires for a segment, the head rides
// along in the same request. So each prefetched sibling gets its own // along in the same request. So each prefetched sibling gets its own
...@@ -865,22 +865,27 @@ describe('prefetch inlining', () => { ...@@ -865,22 +865,27 @@ describe('prefetch inlining', () => {
page = p page = p
}, },
}) })
const act = createRouterAct(page!) const act = createRouterAct(page!, { includeAppShellRequests: true })
// Prefetch and navigate to route A. This caches the layout, the static // Runtime-prefetch (with prefetch={true}) route A. This caches the layout, the
// page, and A's head (riding along with the runtime prefetch), and // static page, and A's head.
// makes A the current page.
await act(async () => { await act(async () => {
await browser await browser
.elementByCss('input[data-link-accordion="/test-independent-head/a"]') .elementByCss('input[data-link-accordion="/test-independent-head/a"]')
.click() .click()
}) }, [
// Shell
{ includes: 'item-layout', kind: 'runtime' },
// Speculative (search params)
{ includes: 'Independent Head Title: a', kind: 'runtime' },
])
// Navigate to A. It should be fully prefetched.
await act(async () => { await act(async () => {
await browser.elementByCss('a[href="/test-independent-head/a"]').click() await browser.elementByCss('a[href="/test-independent-head/a"]').click()
}, 'no-requests') }, 'no-requests')
// Now we're on route A. Reveal the sibling link to route B. The // Now we're on route A. Reveal the sibling link to route B (with prefetch={true}).
// layout is shared between A and B, so it's already cached and won't // The layout is shared between A and B, so it's already cached and won't
// be re-fetched. The only new segment is the [item] page. On this // be re-fetched. The only new segment is the [item] page. On this
// hint-unset route it deopts to the batched runtime prefetch, and B's // hint-unset route it deopts to the batched runtime prefetch, and B's
// param-specific head rides along in the same request — no standalone // param-specific head rides along in the same request — no standalone
...@@ -890,9 +895,7 @@ describe('prefetch inlining', () => { ...@@ -890,9 +895,7 @@ describe('prefetch inlining', () => {
.elementByCss('input[data-link-accordion="/test-independent-head/b"]') .elementByCss('input[data-link-accordion="/test-independent-head/b"]')
.click() .click()
}, [ }, [
// The page below the layout arrives via the runtime prefetch. // The page and the head arrive in the same runtime response.
{ includes: 'page-independent-head', kind: 'runtime' },
// ...and B's head rides along in the same runtime response.
{ includes: 'Independent Head Title: b', kind: 'runtime' }, { includes: 'Independent Head Title: b', kind: 'runtime' },
]) ])
......
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