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
## 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
- [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
......
......@@ -36,16 +36,11 @@ const InstantConfigSchema = z.union([
z.literal(false),
])
const PrefetchSchema = z.enum([
'auto',
'partial',
'unstable_eager',
'force-disabled',
])
const PrefetchSchema = z.enum(['auto', 'partial', 'force-disabled'])
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
// the __GenericInstantConfig type is used to avoid type widening issues with
......@@ -138,9 +133,6 @@ const AppSegmentConfigSchema = z.object({
* - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones. When a static prefetch is insufficient,
* 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.
*/
prefetch: PrefetchSchema.optional(),
......@@ -197,7 +189,7 @@ export function parseAppSegmentConfig(
}
case 'prefetch': {
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': {
......@@ -265,9 +257,6 @@ export type AppSegmentConfig = {
* - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones. When a static prefetch is insufficient,
* 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.
*/
prefetch?: Prefetch
......
......@@ -25,10 +25,10 @@ import {
} from '../../../shared/lib/app-router-types'
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
import { subtreeHasSpeculativePrefetch } from './scheduler'
import { needsSpeculativePrefetch } from './scheduler'
import type { SegmentCacheEntry } from './cache'
import { createCacheMap, type CacheMap } from './cache-map'
import type { FetchStrategy } from './types'
import type { PrefetchTaskFetchStrategy } from './types'
type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'
......@@ -535,19 +535,19 @@ export function getCurrentNavigationGate(): Promise<void> | null {
* 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
* navigation should be allowed to match. A speculative prefetch happens for a
* `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the
* concrete-param entry is genuinely warm and may be matched.
* `<Link prefetch={true}>`, in which case the concrete-param entry is genuinely
* warm and may be matched.
*
* Always returns false outside the testing API, via the aliased
* `navigation-testing-lock.disabled` module.
*/
export function shouldRestrictNavigationToShell(
rootPrefetchHints: number,
linkFetchStrategy: FetchStrategy
linkFetchStrategy: PrefetchTaskFetchStrategy
): boolean {
return (
isNavigationLocked() &&
(rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&
!subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)
!needsSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)
)
}
......@@ -624,8 +624,7 @@ function processQueueInMicrotask() {
// Finished prefetching the route tree. The two-phase (Shell then
// Speculative) flow only applies to routes that have opted into
// Partial Prefetching — either globally via the `partialPrefetching`
// config or per segment (`prefetch: 'partial'` or
// `'unstable_eager'`), all surfaced as the
// config or per segment (`prefetch: 'partial'`), both surfaced as the
// `SubtreeHasPartialPrefetching` hint on the route tree. Every other
// route skips the Shell phase and goes straight to Speculative.
//
......@@ -907,16 +906,14 @@ function pingRootRouteTree(
? FetchStrategy.StaticShell
: FetchStrategy.PPR
// In PPF, links may skip speculative prefetching if they only need a shell.
if (
staticWalkStrategy === FetchStrategy.PPR &&
!subtreeHasSpeculativePrefetch(
!needsSpeculativePrefetch(
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
}
......@@ -1172,17 +1169,11 @@ function pingStaticHead(
* walks prefetch static data and partial entries are acceptable — the
* dynamic holes are filled by the navigation-time request.
*
* Note that on a Partial Prefetching route, non-eager subtrees are still
* 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
* Note: The runtime contract is affordable because most
* routes carry the ShouldAttemptStaticPrefetch hint: their segments are
* prefetched statically and the responses' own sufficiency signal makes a
* runtime request rare. On a hint-unset route, a walked segment deopts
* directly to the batched runtime request — which then serves the segment's
* whole subtree, so navigations into it are complete without a
* navigation-time request.
* directly to the batched runtime request.
*
* This is also the gate for the batched runtime request at the end of
* pingRootRouteTree; requiring runtime completeness does not itself mean a
......@@ -1479,15 +1470,11 @@ function pingNewPartOfCacheComponentsTree(
// runtime data carries it, and the dynamic holes are filled by the
// navigation-time request.
// In PPF, links may skip speculative prefetching if they only need a shell.
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 &&
!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
}
......@@ -2678,24 +2665,21 @@ function doesCurrentSegmentMatchCachedSegment(
}
/**
* Decides whether to skip the speculative prefetch of a subtree. Usually we
* only perform a speculative prefetch if the Link's prefetch prop is set to
* true. However, we also will do a speculative prefetch if the prefetching
* mode of the segment is set to "unstable_eager".
* Decides whether to speculatively prefetch a subtree. Under Partial
* Prefetching we only do this if the Link's prefetch prop is set to true —
* otherwise the subtree relies on the shell that the Shell phase prefetches.
*/
export function subtreeHasSpeculativePrefetch(
fetchStrategy: FetchStrategy,
prefetchHints: number
export function needsSpeculativePrefetch(
taskfetchStrategy: PrefetchTaskFetchStrategy,
rootPrefetchHints: number
): boolean {
return (
// Check if this is a "full" prefetch (<Link prefetch={true}>).
fetchStrategy === FetchStrategy.Full ||
// Check if something in this subtree is configured to be eagerly
// prefetched at the route level. Segments that don't opt into Partial
// Prefetching are marked eager, so a route without any Partial Prefetching
// still speculatively prefetches everything.
(prefetchHints & PrefetchHint.SubtreeHasEagerPrefetch) !== 0
)
if ((rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0) {
// PPF - only needs a speculative prefetch if this is a `<Link prefetch={true}>`.
return taskfetchStrategy === FetchStrategy.Full
} else {
// non-PPF -- all prefetches are speculative.
return true
}
}
// -----------------------------------------------------------------------------
......
......@@ -1099,7 +1099,7 @@ async function generateStagedDynamicFlightRenderResultNode(
// Check if this route should runtime-cache its navigation. This happens when
// 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
// 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
......@@ -1464,7 +1464,6 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
prefetchStage = RenderStage.Static
} else {
if (prefetchMode === PrefetchingMode.Partial) {
// TODO(app-shells): model `partialPrefetching: "unstable_eager"`
// TODO(app-shells): if this navigation came from <Link prefetch={true} />,
// we should show the shell for a speculative prefetch
// (which can have more data than the app shell)
......@@ -2363,7 +2362,7 @@ async function getErrorRSCPayload(
errorHints,
errorPrefetchInliningEnabled,
ctx.missingPrefetchHintPolicy,
ctx.renderOpts.partialPrefetching,
Boolean(ctx.renderOpts.partialPrefetching),
getDynamicParamFromSegment,
query
)
......@@ -3848,7 +3847,7 @@ async function renderToStream(
// embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration. This is enabled when
// 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).
if (
Boolean(renderOpts.partialPrefetching) ||
......@@ -5288,7 +5287,6 @@ async function getPrefetchingModeForPage(
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
// TODO(app-shells): support "unstable_eager"
if (renderOpts.partialPrefetching) {
debug?.('using prefetching mode Partial because of next.config.js')
return PrefetchingMode.Partial
......@@ -5399,7 +5397,7 @@ type StreamRevealStage =
| RenderStage.Runtime
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
return (
navigationKind.type === 'prefetched-client' &&
......
......@@ -191,7 +191,7 @@ async function createComponentTreeInternal(
parseLoaderTree(tree)
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const partialPrefetching = ctx.renderOpts.partialPrefetching
const partialPrefetching = Boolean(ctx.renderOpts.partialPrefetching)
const {
layout,
......
......@@ -61,7 +61,7 @@ export async function computeSegmentPrefetchHints(
hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined,
partialPrefetching: boolean,
// Whether this segment is at or above the root layout (no layout was found
// above it).
isRootLayoutOrAbove: boolean
......@@ -76,11 +76,7 @@ export async function computeSegmentPrefetchHints(
const instantConfig = mod ? (mod as AppSegmentConfig).instant : undefined
const prefetchConfig =
(mod ? (mod as AppSegmentConfig).prefetch : undefined) ??
(partialPrefetching === 'unstable_eager'
? 'unstable_eager'
: partialPrefetching
? 'partial'
: undefined)
(partialPrefetching ? 'partial' : undefined)
let prefetchHints = 0
// Union in the precomputed build-time hints (e.g. segment inlining
......@@ -132,25 +128,10 @@ export async function computeSegmentPrefetchHints(
if (prefetchConfig === 'partial') {
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') {
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
if (loading) {
prefetchHints |= PrefetchHint.SegmentHasLoadingBoundary
......@@ -176,7 +157,7 @@ async function createTransportTreeFromLoaderTreeImpl(
hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
didFindRootLayout: boolean
......@@ -254,7 +235,7 @@ export async function createTransportTreeFromLoaderTree(
hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
// Whether a root layout was already found above this loader tree slice, so a
......@@ -285,7 +266,7 @@ export async function createFullTransportTreeFromLoaderTree(
hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any
): Promise<FullTransportNode> {
......@@ -314,7 +295,7 @@ export async function createRouteTreePrefetch(
hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean | 'unstable_eager' | undefined,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
// See note on createTransportTreeFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false
......
......@@ -51,10 +51,9 @@ export function isFrameworkErrorRoute(route: string | undefined): boolean {
}
/**
* Matches any `prefetch` config that enables Partial Prefetching for the
* segment: 'partial' or 'unstable_eager'. A route with Partial Prefetching
* enabled also runtime-caches its navigations, so this gates the runtime
* prefetch spawn.
* Matches the `prefetch` config that enables Partial Prefetching for the
* segment: 'partial'. A route with Partial Prefetching enabled also
* runtime-caches its navigations, so this gates the runtime prefetch spawn.
*/
export async function anySegmentHasPartialPrefetchingEnabled(
tree: LoaderTree
......@@ -65,7 +64,7 @@ export async function anySegmentHasPartialPrefetchingEnabled(
const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined
if (prefetchConfig === 'partial' || prefetchConfig === 'unstable_eager') {
if (prefetchConfig === 'partial') {
return true
}
......
......@@ -81,7 +81,7 @@ export async function walkTreeWithFlightRouterState({
parsedRequestHeaders,
} = ctx
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const partialPrefetching = ctx.renderOpts.partialPrefetching
const partialPrefetching = Boolean(ctx.renderOpts.partialPrefetching)
const [segment, parallelRoutes, modules] = loaderTreeToFilter
......
......@@ -805,9 +805,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
pageExtensions: z.array(z.string()).min(1).optional(),
instrumentationClientInject: z.array(z.string()).optional(),
partialPrefetching: z
.union([z.boolean(), z.literal('unstable_eager')])
.optional(),
partialPrefetching: z.boolean().optional(),
poweredByHeader: z.boolean().optional(),
productionBrowserSourceMaps: z.boolean().optional(),
reactCompiler: z.union([
......
......@@ -2015,12 +2015,8 @@ export interface NextConfig {
*
* When `false` or omitted, this does nothing (the legacy behavior, where
* 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?: {
[profile: string]: {
......
......@@ -68,16 +68,14 @@ export function logExperimentalInfo({
}: {
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
partialPrefetching?: boolean | 'unstable_eager'
partialPrefetching?: boolean
}) {
if (cacheComponents) {
Log.bootstrap(`- Cache Components enabled`)
}
if (partialPrefetching) {
const mode =
partialPrefetching === 'unstable_eager' ? ' (unstable_eager)' : ''
Log.bootstrap(`- Partial Prefetching enabled${mode}`)
Log.bootstrap(`- Partial Prefetching enabled`)
}
if (experimentalFeatures?.length) {
......
......@@ -22,8 +22,8 @@ export type ServerInitResult = {
experimentalFeatures: ConfiguredExperimentalFeature[]
// Whether cache components is enabled
cacheComponents: boolean
// Whether partial prefetching is enabled (and its mode)
partialPrefetching?: boolean | 'unstable_eager'
// Whether partial prefetching is enabled
partialPrefetching?: boolean
// Whether AGENTS.md / CLAUDE.md auto-generation is enabled (default true)
agentRules?: boolean
// Whether the development server memory threshold restart is enabled
......@@ -107,7 +107,7 @@ async function initializeImpl(opts: {
distDir: string
experimentalFeatures: ConfiguredExperimentalFeature[]
cacheComponents: boolean
partialPrefetching?: boolean | 'unstable_eager'
partialPrefetching?: boolean
devMemoryThresholdRestart: boolean
}): Promise<ServerInitResult> {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER
......
......@@ -159,16 +159,11 @@ const API_DOCS: Record<
prefetch: {
description: `Controls prefetching behavior for this segment. Some options are experimental and may change.`,
link: '(docs coming soon)',
type: `"auto" | "partial" | "unstable_eager" | "force-disabled"`,
type: `"auto" | "partial" | "force-disabled"`,
options: {
auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.',
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.',
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.',
},
insertText: `prefetch = 'partial';`,
......
......@@ -189,9 +189,9 @@ export const enum PrefetchHint {
// This segment or one of its descendants opts into Partial Prefetching, i.e.
// uses the two-phase (Shell then Speculative) prefetch flow. Set when
// `prefetch` is 'partial' or 'unstable_eager' (including the defaults
// implied by the global `partialPrefetching` config). Propagates upward so
// the root segment reflects the entire subtree.
// `prefetch` is 'partial' (including the default implied by the global
// `partialPrefetching` config). Propagates upward so the root segment
// reflects the entire subtree.
//
// Partial Prefetching segments require RUNTIME COMPLETENESS: a prefetch
// isn't considered done for such a segment until an entry at least as
......@@ -246,12 +246,10 @@ export const enum PrefetchHint {
// (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse
// it without considering caches populated by older builds.
// This segment or one of its descendants prefetches "eagerly" — i.e. its
// effective prefetch strategy is anything other than 'partial'. Used by
// the scheduler's phasing: a non-eager subtree relies on the shell the
// Shell phase prefetches and skips its Speculative prefetch. Propagates
// upward so the root reflects the entire subtree.
SubtreeHasEagerPrefetch = 0b1000000000000,
// NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch
// (prefetch: 'unstable_eager', plus every segment that did not opt into
// Partial Prefetching). After `unstable_eager` was removed, it's no longer needed.
// This segment or one of its descendants exports `instant = false`,
// explicitly opting out of Partial Prefetching. Propagates upward so the root
// reflects the entire subtree. Used only to suppress the dev-time
......@@ -311,8 +309,7 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const SubtreePrefetchHints =
PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasLoadingBoundary |
PrefetchHint.SubtreeHasInstantFalse |
PrefetchHint.SubtreeHasEagerPrefetch
PrefetchHint.SubtreeHasInstantFalse
/**
* Folds a child segment's prefetch hints into its parent's, propagating the
......@@ -342,13 +339,8 @@ export function propagateSubtreeBits(
) {
parentHints |= PrefetchHint.SubtreeHasLoadingBoundary
}
// And for eager prefetch. The bit is set directly on each eager 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.
// And for `instant = false`. The bit is set directly on each opted-out
// segment, so there's no separate segment-local flag — propagate it as-is.
if (childHints & PrefetchHint.SubtreeHasInstantFalse) {
parentHints |= PrefetchHint.SubtreeHasInstantFalse
}
......
......@@ -991,11 +991,11 @@ describe('cached navigations', () => {
})
})
// A `prefetch` config that enables Partial Prefetching ('partial' or
// 'unstable_eager') also opts the route into runtime Cached Navigations,
// even though this fixture does not set the global `partialPrefetching`
// flag. Contrast with `partially-static`, which has no `prefetch` config
// and only gets static caching.
// A `prefetch` config that enables Partial Prefetching ('partial') also opts
// the route into runtime Cached Navigations, even though this fixture does
// not set the global `partialPrefetching` flag. Contrast with
// `partially-static`, which has no `prefetch` config and only gets static
// caching.
async function expectRuntimeCachedOnSecondNavigation(route: string) {
let page: Playwright.Page
const browser = await next.browser('/', {
......@@ -1057,8 +1057,4 @@ describe('cached navigations', () => {
it('runtime-caches a route with prefetch = "partial"', async () => {
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() {
Go to prefetch=partial page
</Link>
</li>
<li>
<Link href="/prefetch-eager" prefetch={false}>
Go to prefetch=unstable_eager page
</Link>
</li>
</ul>
</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() {
</li>
</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>
<ul>
<li>
......
......@@ -30,7 +30,7 @@ export default async function Page({
return (
<div>
<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}
</LinkAccordion>
</div>
......
......@@ -644,7 +644,7 @@ describe('prefetch inlining', () => {
// route's static-attempt hint is unset because the page reads cookies,
// so the walked layout deopts directly to the batched runtime shell,
// 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
// runtime-complete entry is never re-fetched by a static prefetch.)
await act(
......@@ -720,7 +720,7 @@ describe('prefetch inlining', () => {
},
// The layout reads cookies, so the route's static-attempt hint is
// 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
// response. No static bundle request fires: every entry was already
// runtime-cached at the shell tier by the Shell phase, and a
......@@ -820,7 +820,7 @@ describe('prefetch inlining', () => {
.click()
},
// 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.
{ includes: 'Runtime parallel main content', kind: 'runtime' }
)
......@@ -842,8 +842,8 @@ describe('prefetch inlining', () => {
// [item] param and searchParams, making it depend on runtime data.
//
// Because the layout reads cookies, the route's static-attempt hint is
// unset, so on this Partial Prefetching route every per-link prefetch
// deopts its new subtree to the batched runtime prefetch. The head is
// unset, so on this Partial Prefetching route every shell and prefetch
// deopt its new subtree to a runtime request. The head is
// param-dependent, so it is NOT part of the reusable App Shell — but
// whenever a runtime prefetch fires for a segment, the head rides
// along in the same request. So each prefetched sibling gets its own
......@@ -865,22 +865,27 @@ describe('prefetch inlining', () => {
page = p
},
})
const act = createRouterAct(page!)
const act = createRouterAct(page!, { includeAppShellRequests: true })
// Prefetch and navigate to route A. This caches the layout, the static
// page, and A's head (riding along with the runtime prefetch), and
// makes A the current page.
// Runtime-prefetch (with prefetch={true}) route A. This caches the layout, the
// static page, and A's head.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/test-independent-head/a"]')
.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 browser.elementByCss('a[href="/test-independent-head/a"]').click()
}, 'no-requests')
// Now we're on route A. Reveal the sibling link to route B. The
// layout is shared between A and B, so it's already cached and won't
// Now we're on route A. Reveal the sibling link to route B (with prefetch={true}).
// 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
// hint-unset route it deopts to the batched runtime prefetch, and B's
// param-specific head rides along in the same request — no standalone
......@@ -890,9 +895,7 @@ describe('prefetch inlining', () => {
.elementByCss('input[data-link-accordion="/test-independent-head/b"]')
.click()
}, [
// The page below the layout arrives via the runtime prefetch.
{ includes: 'page-independent-head', kind: 'runtime' },
// ...and B's head rides along in the same runtime response.
// The page and the head arrive in the same runtime response.
{ 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