Unverified Commit 64328fe9 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Track vary params during static prerendering (#89267)

During prerendering, track which route params each segment accesses.
Params that are NOT accessed can be omitted from the client router's
cache key for that segment, allowing it to be shared across multiple
pages and reducing the number of prefetch requests.

For example, if a page at /shop/[category]/[itemId] only accesses
`category` but not `itemId`, navigating between /shop/electronics/phone
and /shop/electronics/tablet can reuse the same cached page segment,
since only `category` affects its output.

Most of the client-side changes were already implemented in previous
PRs; the core mechanism was already being used for omitting search
params from the cache keys of static segments. This generalizes the
mechanism for all params. So this PR is primarily about adding per-param
tracking on the server and wiring up the logic to send the params to the
client.

Each segment's CacheNodeSeedData contains its own VaryParamsThenable
that resolves to a Set<string> of accessed param names. The thenable is
a mutable tracker during render that accumulates param accesses, then
resolves when rendering completes. The response also includes an `h`
field for head vary params, which tracks params accessed by
generateMetadata/generateViewport separately from segment body access.

The trickiest part of this implementation is the timing. The vary params
thenables represent metadata about the response, but they're also part
of the response itself - they're streamed alongside the segment data. We
can't know which params were accessed until rendering completes, but we
need to resolve all thenables before aborting the stream, or else the
client would block waiting for data that will never arrive.

We address this on both sides. On the server, we resolve all thenables
immediately before aborting. On the client, we read vary params
synchronously using a React Flight optimization: calling
thenable.then(noop) forces Flight to transition from 'resolved_model' to
'fulfilled' without scheduling a microtask. If the thenable still isn't
fulfilled after this, we fall back to null (unknown) rather than
blocking. This ensures the client never suspends on these thenables,
providing a safe fallback if something goes wrong with server timing.

A key distinction is null vs empty Set. An empty Set means the segment
accesses no params and can be shared across all param values - this is
the case for client components (when Cache Components is enabled),
segments without user code, etc. A null value means tracking failed -
either because it's not wired up yet (like runtime prefetches), or due
to some edge case where the thenables weren't resolved in time.

For segments where we know upfront that no params will be accessed, we
use a singleton emptyVaryParamsTracker that's already resolved. This
ensures these segments resolve correctly even if other tracking fails.

In the future, we'll likely optimize the response format by sending a
bitmask instead of a Set of param names. But this is mostly just an
optimization — sending the Set doesn't expose anything new since the
param names are already embedded in the route tree (although that's also
something we could obfuscate in the future).

This does not yet implement vary param tracking during runtime
prefetches - the abort timing needs additional coordination. Deferred to
a separate PR.
parent 0ed1edd8
......@@ -7,6 +7,10 @@ import type {
CacheNodeSeedData,
Segment as FlightRouterStateSegment,
} from '../../../shared/lib/app-router-types'
import {
readVaryParams,
type VaryParams,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
import { HasLoadingBoundary } from '../../../shared/lib/app-router-types'
import {
NEXT_DID_POSTPONE_HEADER,
......@@ -1756,6 +1760,13 @@ export async function fetchRouteOnCacheMiss(
return null
}
// Read head vary params synchronously. Individual segments carry their
// own thenables in CacheNodeSeedData.
const headVaryParamsThenable = serverData.h
const headVaryParams =
headVaryParamsThenable !== null
? readVaryParams(headVaryParamsThenable)
: null
writeDynamicTreeResponseIntoCache(
Date.now(),
task,
......@@ -1768,6 +1779,7 @@ export async function fetchRouteOnCacheMiss(
couldBeIntercepted,
canonicalUrl,
routeIsPPREnabled,
headVaryParams,
pathname
)
}
......@@ -2049,6 +2061,13 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
: // Full and LoadingBoundary prefetches cannot have holes.
// (even if we did set the prefetch header, we only use this codepath for non-PPR-enabled routes)
false
// Read head vary params synchronously. Individual segments carry their
// own thenables in CacheNodeSeedData.
const headVaryParamsThenable = serverData.h
const headVaryParams =
headVaryParamsThenable !== null
? readVaryParams(headVaryParamsThenable)
: null
// Aside from writing the data into the cache, this function also returns
// the entries that were fulfilled, so we can streamingly update their sizes
......@@ -2060,6 +2079,7 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
response as RSCResponse<NavigationFlightResponse>,
serverData,
isResponsePartial,
headVaryParams,
route,
spawnedEntries
)
......@@ -2086,8 +2106,9 @@ function writeDynamicTreeResponseIntoCache(
couldBeIntercepted: boolean,
canonicalUrl: string,
routeIsPPREnabled: boolean,
headVaryParams: VaryParams | null,
originalPathname: string
) {
): void {
const renderedSearch = getRenderedSearch(response)
const normalizedFlightDataResult = normalizeFlightData(serverData.f)
......@@ -2160,6 +2181,7 @@ function writeDynamicTreeResponseIntoCache(
response,
serverData,
isResponsePartial,
headVaryParams,
fulfilledEntry,
null
)
......@@ -2190,6 +2212,7 @@ function writeDynamicRenderResponseIntoCache(
response: RSCResponse<NavigationFlightResponse>,
serverData: NavigationFlightResponse,
isResponsePartial: boolean,
headVaryParams: VaryParams | null,
route: FulfilledRouteCacheEntry,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
): Array<FulfilledSegmentCacheEntry> | null {
......@@ -2261,12 +2284,14 @@ function writeDynamicRenderResponseIntoCache(
const head = flightData.head
if (head !== null) {
// For head entries, use the head-specific vary params passed as parameter.
fulfillEntrySpawnedByRuntimePrefetch(
now,
fetchStrategy,
head,
flightData.isHeadPartial,
staleAt,
headVaryParams,
route.metadata,
spawnedEntries
)
......@@ -2310,12 +2335,19 @@ function writeSeedDataIntoCache(
// (CacheNodeSeedData) into the prefetch cache.
const rsc = seedData[0]
const isPartial = rsc === null || isResponsePartial
const varyParamsThenable = seedData[5]
// Each segment carries its own vary params thenable in the seed data. The
// thenable resolves to the set of params the segment accessed during render.
// A null thenable means tracking was not enabled (not a prerender).
const varyParams =
varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null
fulfillEntrySpawnedByRuntimePrefetch(
now,
fetchStrategy,
rsc,
isPartial,
staleAt,
varyParams,
tree,
entriesOwnedByCurrentTask
)
......@@ -2353,6 +2385,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
rsc: React.ReactNode,
isPartial: boolean,
staleAt: number,
segmentVaryParams: Set<string> | null,
tree: RouteTree,
entriesOwnedByCurrentTask: Map<
SegmentRequestKey,
......@@ -2367,7 +2400,26 @@ function fulfillEntrySpawnedByRuntimePrefetch(
? entriesOwnedByCurrentTask.get(tree.requestKey)
: undefined
if (ownedEntry !== undefined) {
fulfillSegmentCacheEntry(ownedEntry, rsc, staleAt, isPartial)
const fulfilledEntry = fulfillSegmentCacheEntry(
ownedEntry,
rsc,
staleAt,
isPartial
)
// Re-key the entry based on which params the segment actually depends on.
if (segmentVaryParams !== null) {
const fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
segmentVaryParams
)
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
fulfilledVaryPath,
fulfilledEntry,
isRevalidation
)
}
} else {
// There's no matching entry. Attempt to create a new one.
const possiblyNewEntry = readOrCreateSegmentCacheEntry(
......@@ -2378,12 +2430,26 @@ function fulfillEntrySpawnedByRuntimePrefetch(
if (possiblyNewEntry.status === EntryStatus.Empty) {
// Confirmed this is a new entry. We can fulfill it.
const newEntry = possiblyNewEntry
fulfillSegmentCacheEntry(
const fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(newEntry, fetchStrategy),
rsc,
staleAt,
isPartial
)
// Re-key the entry based on which params the segment actually depends on.
if (segmentVaryParams !== null) {
const fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
segmentVaryParams
)
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
fulfilledVaryPath,
fulfilledEntry,
isRevalidation
)
}
} else {
// There was already an entry in the cache. But we may be able to
// replace it with the new one from the server.
......@@ -2396,11 +2462,13 @@ function fulfillEntrySpawnedByRuntimePrefetch(
staleAt,
isPartial
)
upsertSegmentEntry(
now,
getSegmentVaryPathForRequest(fetchStrategy, tree),
newEntry
)
// Use the fulfilled vary path if available, otherwise fall back to
// the request vary path.
const varyPath =
segmentVaryParams !== null
? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams)
: getSegmentVaryPathForRequest(fetchStrategy, tree)
upsertSegmentEntry(now, varyPath, newEntry)
}
}
}
......
......@@ -119,6 +119,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
m: fallbackInitialRSCPayload.m,
G: fallbackInitialRSCPayload.G,
S: fallbackInitialRSCPayload.S,
h: fallbackInitialRSCPayload.h,
}
}
......
......@@ -179,6 +179,11 @@ import {
} from './work-unit-async-storage.external'
import { consoleAsyncStorage } from './console-async-storage.external'
import { CacheSignal } from './cache-signal'
import {
createResponseVaryParamsAccumulator,
finishAccumulatingVaryParams,
getMetadataVaryParamsThenable,
} from './vary-params'
import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -564,6 +569,7 @@ async function generateDynamicRSCPayload(
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
}
// For runtime prefetches, we encode the stale time and isPartial flag in the response body
......@@ -1052,6 +1058,8 @@ async function prospectiveRuntimeServerPrerender(
renderResumeDataCache,
prerenderResumeDataCache,
hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null,
// We only need task sequencing in the final prerender.
runtimeStagePromise: null,
// These are not present in regular prerenders, but allowed in a runtime prerender.
......@@ -1298,6 +1306,8 @@ async function finalRuntimeServerPrerender(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// TODO: Enable vary params tracking for runtime prefetches.
varyParamsAccumulator: null,
// Used to separate the "Static" stage from the "Runtime" stage.
runtimeStagePromise,
// These are not present in regular prerenders, but allowed in a runtime prerender.
......@@ -1554,6 +1564,7 @@ async function getRSCPayload(
m: missingSlots,
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
}
}
......@@ -1679,6 +1690,7 @@ async function getErrorRSCPayload(
],
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
} satisfies InitialRSCPayload
}
......@@ -3817,6 +3829,8 @@ async function warmupModuleCacheForRuntimeValidationInDev(
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
}
const runtimeServerStream = createNodeStreamFromChunks(
......@@ -3960,6 +3974,8 @@ async function validateStagedShell(
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
}
let runtimeDynamicValidation = createDynamicValidationState()
......@@ -4319,6 +4335,8 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null,
}
// We're not going to use the result of this render because the only time it could be used
......@@ -4352,6 +4370,8 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null,
})
const pendingInitialServerResult = workUnitAsyncStorage.run(
......@@ -4471,6 +4491,8 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
}
const prerender = (
......@@ -4571,6 +4593,8 @@ async function prerenderToStream(
const finalServerReactController = new AbortController()
const finalServerRenderController = new AbortController()
const varyParamsAccumulator = createResponseVaryParamsAccumulator()
const finalServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender',
phase: 'render',
......@@ -4595,6 +4619,7 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator,
}
const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
......@@ -4629,6 +4654,7 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator,
})
let prerenderIsPending = true
......@@ -4669,7 +4695,20 @@ async function prerenderToStream(
return prerenderResult
},
() => {
async () => {
// Now that the prerendering is complete, we know which vary
// params were used to compute the response. Resolve the vary
// params thenable so it can be sent to the client. The timing
// here is important: the thenable was included in the Flight
// payload, but it can only be serialized at the very end, after
// all the components have finished.
//
// We resolve the accumulator directly here instead of reading from
// the work unit store because this callback runs in a separate
// task (via setTimeout) and may not have access to the async
// storage context.
await finishAccumulatingVaryParams(varyParamsAccumulator)
if (finalServerReactController.signal.aborted) {
// If the server controller is already aborted we must have called something
// that required aborting the prerender synchronously such as with new Date()
......@@ -4714,6 +4753,8 @@ async function prerenderToStream(
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
}
let dynamicValidation = createDynamicValidationState()
......
......@@ -6,6 +6,7 @@ import type {
DynamicParamTypesShort,
HeadData,
} from '../../shared/lib/app-router-types'
import { readVaryParams } from '../../shared/lib/segment-cache/vary-params-decoding'
import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin'
// eslint-disable-next-line import/no-extraneous-dependencies
......@@ -245,6 +246,15 @@ async function PrefetchTreeData({
const seedData: CacheNodeSeedData = flightDataPaths[0][1]
const head: HeadData = flightDataPaths[0][2]
// Extract the head vary params from the decoded response.
// The head vary params thenable should be fulfilled by now; if not, treat
// as unknown (null).
const headVaryParamsThenable = initialRSCPayload.h
const headVaryParams =
headVaryParamsThenable !== null
? readVaryParams(headVaryParamsThenable)
: null
// Compute the route metadata tree by traversing the FlightRouterState. As we
// walk the tree, we will also spawn a task to produce a prefetch response for
// each segment.
......@@ -270,9 +280,7 @@ async function PrefetchTreeData({
staleTime,
head,
HEAD_REQUEST_KEY,
// TODO: Track vary params for metadata. For now, assume all
// params vary.
null,
headVaryParams,
clientModules
)
)
......@@ -336,7 +344,15 @@ function collectSegmentDataImpl(
}
const hasRuntimePrefetch = seedData !== null ? seedData[4] : false
const varyParams = seedData !== null ? seedData[5] : null
// Determine which params this segment varies on.
// Read the vary params thenable directly from the seed data. By the time
// collectSegmentData runs, the thenable should be fulfilled. If it's not
// fulfilled or null, treat as unknown (null means we can't share cache
// entries across param values).
const varyParamsThenable = seedData !== null ? seedData[5] : null
const varyParams =
varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null
if (seedData !== null) {
// Spawn a task to write the segment data to a new Flight stream.
......
......@@ -23,6 +23,12 @@ import { NextNodeServerSpan } from '../lib/trace/constants'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import {
createVaryParamsAccumulator,
emptyVaryParamsAccumulator,
getVaryParamsThenable,
type VaryParamsAccumulator,
} from './vary-params'
import type {
UseCacheLayoutProps,
UseCachePageProps,
......@@ -672,8 +678,6 @@ async function createComponentTreeInternal(
// When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component
if (!MaybeComponent) {
// No user-provided component at this level, so no params are accessed.
const emptyVaryParams = new Set<string>()
return createSeedData(
ctx,
createElement(
......@@ -688,7 +692,9 @@ async function createComponentTreeInternal(
loadingData,
isPossiblyPartialResponse,
hasRuntimePrefetch,
emptyVaryParams
// No user-provided component, so no params will be accessed. Use the
// pre-resolved empty tracker.
emptyVaryParamsAccumulator
)
}
......@@ -709,8 +715,6 @@ async function createComponentTreeInternal(
workStore.forceDynamic &&
experimental.isRoutePPREnabled
) {
// force-dynamic segments can't have their vary params tracked
const unknownVaryParams = null
return createSeedData(
ctx,
createElement(
......@@ -728,21 +732,20 @@ async function createComponentTreeInternal(
loadingData,
true,
hasRuntimePrefetch,
unknownVaryParams
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator
)
}
const isClientComponent = isClientReference(layoutOrPageMod)
const varyParams =
const varyParamsAccumulator =
isClientComponent && cacheComponents
? // Client components with Cache Components enabled don't receive params
// from the server, so they have an empty vary params set.
new Set<string>()
: // TODO: Server segments don't yet track which params are accessed.
// So for now we must assume that all params may vary (null represents
// unknown vary params, not an empty set).
null
emptyVaryParamsAccumulator
: createVaryParamsAccumulator()
if (
process.env.NODE_ENV === 'development' &&
......@@ -794,13 +797,18 @@ async function createComponentTreeInternal(
// their usage in case the current render mode tracks dynamic API usage.
const params = createServerParamsForServerSegment(
currentParams,
workStore
workStore,
varyParamsAccumulator
)
// If we are passing searchParams to a server component Page we need to
// track their usage in case the current render mode tracks dynamic API
// usage.
let searchParams = createServerSearchParamsForServerPage(query, workStore)
let searchParams = createServerSearchParamsForServerPage(
query,
workStore,
varyParamsAccumulator
)
if (isUseCacheFunction(PageComponent)) {
const UseCachePageComponent: ComponentType<UseCachePageProps> =
......@@ -852,7 +860,7 @@ async function createComponentTreeInternal(
loadingData,
isPossiblyPartialResponse,
hasRuntimePrefetch,
varyParams
varyParamsAccumulator
)
} else {
const SegmentComponent = Component
......@@ -970,7 +978,8 @@ async function createComponentTreeInternal(
} else {
const params = createServerParamsForServerSegment(
currentParams,
workStore
workStore,
varyParamsAccumulator
)
let serverSegment: React.ReactNode
......@@ -1066,7 +1075,7 @@ async function createComponentTreeInternal(
loadingData,
isPossiblyPartialResponse,
hasRuntimePrefetch,
varyParams
varyParamsAccumulator
)
}
}
......@@ -1218,7 +1227,7 @@ function createSeedData(
loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean,
hasRuntimePrefetch: boolean,
varyParams: Set<string> | null
varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData {
if (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an
......@@ -1239,6 +1248,6 @@ function createSeedData(
null,
isPossiblyPartialResponse,
hasRuntimePrefetch,
varyParams,
varyParamsAccumulator ? getVaryParamsThenable(varyParamsAccumulator) : null,
]
}
import type { Params } from '../request/params'
import type { SearchParams } from '../request/search-params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import type {
VaryParamsThenable,
VaryParams,
} from '../../shared/lib/segment-cache/vary-params-decoding'
/**
* Accumulates vary params for a single segment (or for metadata/rootParams).
*
* VaryParamsAccumulator is also a thenable that can be serialized by React
* Flight. The accumulator starts as 'pending' and accumulates param accesses
* during render. Call `finishTrackingVaryParams()` after rendering to resolve
* all accumulators.
*
* The `status` and `value` fields follow the React Flight thenable protocol:
* when `status === 'fulfilled'`, Flight can read `value` synchronously without
* scheduling a microtask via `.then()`.
*/
export type VaryParamsAccumulator = {
// Mutable during render - accumulates param access
varyParams: VaryParams
// React thenable protocol fields
status: 'pending' | 'fulfilled'
value: VaryParams
then(
onfulfilled?: ((value: Set<string>) => unknown) | null,
onrejected?: ((reason: unknown) => unknown) | null
): void
// Internal - callbacks waiting for resolution
resolvers: Array<(value: Set<string>) => void>
}
/**
* A mutable data structure for accumulating per-segment vary params for an
* entire server response. It's only used during prerenders. It describes
* metadata about the response itself.
*/
export type ResponseVaryParamsAccumulator = {
/** Vary params accumulator for metadata/viewport (the "head" segment) */
head: VaryParamsAccumulator
/** Vary params accumulator for root params access */
rootParams: VaryParamsAccumulator
/** Vary params accumulators for each route segment */
segments: Set<VaryParamsAccumulator>
}
function createSegmentVaryParamsAccumulator(): VaryParamsAccumulator {
const accumulator: VaryParamsAccumulator = {
varyParams: new Set(),
status: 'pending',
value: new Set(),
then(onfulfilled: ((value: Set<string>) => unknown) | null | undefined) {
if (onfulfilled) {
if (accumulator.status === 'pending') {
accumulator.resolvers.push(onfulfilled)
} else {
onfulfilled(accumulator.value)
}
}
},
resolvers: [],
}
return accumulator
}
/**
* A singleton accumulator that's already resolved to an empty Set. Use this for
* segments where we know upfront that no params will be accessed, such as
* client components or segments without user code.
*
* Benefits:
* - No need to accumulate or resolve later
* - Resilient: resolves correctly even if other tracking fails
* - Memory efficient: reuses the same object
*/
const emptySet: VaryParams = new Set()
export const emptyVaryParamsAccumulator: VaryParamsAccumulator = {
varyParams: emptySet,
status: 'fulfilled',
value: emptySet,
then(onfulfilled: ((value: Set<string>) => unknown) | null | undefined) {
if (onfulfilled) {
onfulfilled(emptySet)
}
},
resolvers: [],
}
export function createResponseVaryParamsAccumulator(): ResponseVaryParamsAccumulator {
// Create the head and rootParams accumulators as top-level fields.
// Segment accumulators are added to the segments set as they are created.
const head = createSegmentVaryParamsAccumulator()
const rootParams = createSegmentVaryParamsAccumulator()
const segments = new Set<VaryParamsAccumulator>()
return {
head,
rootParams,
segments,
}
}
/**
* Allocates a new VaryParamsAccumulator and adds it to the response accumulator
* associated with the current WorkUnitStore.
*
* Returns a thenable that resolves to the segment's vary params once rendering
* is complete. The thenable can be passed directly to React Flight for
* serialization.
*/
export function createVaryParamsAccumulator(): VaryParamsAccumulator | null {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime': {
const responseAccumulator = workUnitStore.varyParamsAccumulator
if (responseAccumulator !== null) {
const accumulator = createSegmentVaryParamsAccumulator()
responseAccumulator.segments.add(accumulator)
return accumulator
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return null
}
export function getMetadataVaryParamsAccumulator(): VaryParamsAccumulator | null {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime': {
const responseAccumulator = workUnitStore.varyParamsAccumulator
if (responseAccumulator !== null) {
return responseAccumulator.head
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'unstable-cache':
return null
default:
workUnitStore satisfies never
}
}
return null
}
export function getVaryParamsThenable(
accumulator: VaryParamsAccumulator
): VaryParamsThenable | null {
return accumulator as unknown as VaryParamsThenable | null
}
export function getMetadataVaryParamsThenable(): VaryParamsThenable | null {
const accumulator = getMetadataVaryParamsAccumulator()
if (accumulator !== null) {
return getVaryParamsThenable(accumulator)
}
return null
}
// The metadata and viewport are always delivered in a single payload, so they
// don't need to be tracked separately. This may change in the future, but for
// now this is just an alias.
export const getViewportVaryParamsAccumulator = getMetadataVaryParamsAccumulator
export function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | null {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime': {
const responseAccumulator = workUnitStore.varyParamsAccumulator
if (responseAccumulator !== null) {
return responseAccumulator.rootParams
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'unstable-cache':
return null
default:
workUnitStore satisfies never
}
}
return null
}
/**
* Records that a param was accessed. Adds the param name to the accumulator's
* varyParams set.
*/
export function accumulateVaryParam(
accumulator: VaryParamsAccumulator,
paramName: string
): void {
accumulator.varyParams.add(paramName)
}
/**
* Records a root param access.
*/
export function accumulateRootVaryParam(paramName: string): void {
const rootParamsAccumulator = getRootParamsVaryParamsAccumulator()
if (rootParamsAccumulator !== null) {
accumulateVaryParam(rootParamsAccumulator, paramName)
}
}
export function createVaryingParams(
accumulator: VaryParamsAccumulator,
originalParamsObject: Params
): Params {
const underlyingParamsWithVarying: Params = {}
for (const paramName in originalParamsObject) {
Object.defineProperty(underlyingParamsWithVarying, paramName, {
get() {
accumulateVaryParam(accumulator, paramName)
return originalParamsObject[paramName]
},
enumerable: true,
})
}
return underlyingParamsWithVarying
}
export function createVaryingSearchParams(
accumulator: VaryParamsAccumulator,
originalSearchParamsObject: SearchParams
): SearchParams {
const underlyingSearchParamsWithVarying: SearchParams = {}
for (const searchParamName in originalSearchParamsObject) {
Object.defineProperty(underlyingSearchParamsWithVarying, searchParamName, {
get() {
// TODO: Unlike path params, we don't vary track each search param
// individually. The entire search string is treated as a single param.
// This may change in the future.
accumulateVaryParam(accumulator, '?')
return originalSearchParamsObject[searchParamName]
},
enumerable: true,
})
}
return underlyingSearchParamsWithVarying
}
/**
* Resolves all segment accumulators in a ResponseVaryParamsAccumulator with
* their final vary params. Call this after rendering is complete.
*
* Each segment's thenable is resolved with its vary params merged with the
* root params. If we can't track vary params (e.g., legacy prerender), simply
* don't call this function - the client treats unresolved thenables as
* "unknown" vary params.
*/
export async function finishAccumulatingVaryParams(
responseAccumulator: ResponseVaryParamsAccumulator
): Promise<void> {
const rootVaryParams = responseAccumulator.rootParams.varyParams
// Resolve head
finishSegmentAccumulator(responseAccumulator.head, rootVaryParams)
// Resolve each segment
for (const segmentAccumulator of responseAccumulator.segments) {
finishSegmentAccumulator(segmentAccumulator, rootVaryParams)
}
// Now that the thenables are resolved, Flight should be able to flush the
// vary params into the response stream. This work gets scheduled internally
// by Flight using a microtask as soon as we notify the thenable listeners.
//
// We need to ensure that Flight's pending queues are emptied before this
// function returns; the caller will abort the prerender immediately after.
// We can't use a macrotask, because that would allow dynamic IO to sneak
// into the response. So we use microtasks instead.
//
// The exact number of awaits here isn't important (indeed, one seems to be
// sufficient, at the time of writing), as long as we wait enough ticks for
// Flight to finish writing the response.
//
// Anything that remains in Flight's internal queue after these awaits must
// be actual dynamic IO, not caused by pending vary params tasks. In other
// words, failing to do this would cause us to treat a fully static prerender
// as if it were partially dynamic.
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
}
function finishSegmentAccumulator(
accumulator: VaryParamsAccumulator,
rootVaryParams: VaryParams
): void {
if (accumulator.status !== 'pending') {
return
}
const merged = new Set<string>(accumulator.varyParams)
for (const param of rootVaryParams) {
merged.add(param)
}
accumulator.value = merged
accumulator.status = 'fulfilled'
for (const resolver of accumulator.resolvers) {
resolver(merged)
}
accumulator.resolvers = []
}
......@@ -4,6 +4,7 @@ import type { ResponseCookies } from '../web/spec-extension/cookies'
import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
import type { CacheSignal } from './cache-signal'
import type { ResponseVaryParamsAccumulator } from './vary-params'
import type { DynamicTrackingState } from './dynamic-rendering'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
......@@ -207,6 +208,13 @@ interface PrerenderStoreModernCommon
* subsequent dynamic render.
*/
readonly hmrRefreshHash: string | undefined
/**
* A mutable accumulator for per-segment vary params during prerender. Tracks
* which route params each segment actually accesses, allowing the client
* cache to re-key entries for better sharing across different param values.
*/
readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null
}
interface StaticPrerenderStoreCommon {
......
......@@ -3,6 +3,11 @@ import {
type WorkStore,
} from '../app-render/work-async-storage.external'
import type { OpaqueFallbackRouteParams } from './fallback-params'
import type { VaryParamsAccumulator } from '../app-render/vary-params'
import {
createVaryingParams,
getMetadataVaryParamsAccumulator,
} from '../app-render/vary-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
......@@ -48,10 +53,15 @@ export function createParamsFromClient(
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
// Client params don't need additional vary tracking because by the
// time they reach the client, the access would have already been
// tracked by the server.
const varyParamsAccumulator = null
return createStaticPrerenderParams(
underlyingParams,
workStore,
workUnitStore
workUnitStore,
varyParamsAccumulator
)
case 'cache':
case 'private-cache':
......@@ -87,12 +97,23 @@ export function createParamsFromClient(
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
export type CreateServerParamsForMetadata = typeof createServerParamsForMetadata
export const createServerParamsForMetadata = createServerParamsForServerSegment
export function createServerParamsForMetadata(
underlyingParams: Params,
workStore: WorkStore
): Promise<Params> {
const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()
return createServerParamsForServerSegment(
underlyingParams,
workStore,
metadataVaryParamsAccumulator
)
}
// routes always runs in RSC context so it is equivalent to a Server Page Component
export function createServerParamsForRoute(
underlyingParams: Params,
workStore: WorkStore
workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
......@@ -104,7 +125,8 @@ export function createServerParamsForRoute(
return createStaticPrerenderParams(
underlyingParams,
workStore,
workUnitStore
workUnitStore,
varyParamsAccumulator
)
case 'cache':
case 'private-cache':
......@@ -113,7 +135,11 @@ export function createServerParamsForRoute(
'createServerParamsForRoute should not be called in cache contexts.'
)
case 'prerender-runtime':
return createRuntimePrerenderParams(underlyingParams, workUnitStore)
return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
)
case 'request':
if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev`
......@@ -138,7 +164,8 @@ export function createServerParamsForRoute(
export function createServerParamsForServerSegment(
underlyingParams: Params,
workStore: WorkStore
workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
......@@ -150,7 +177,8 @@ export function createServerParamsForServerSegment(
return createStaticPrerenderParams(
underlyingParams,
workStore,
workUnitStore
workUnitStore,
varyParamsAccumulator
)
case 'cache':
case 'private-cache':
......@@ -159,7 +187,11 @@ export function createServerParamsForServerSegment(
'createServerParamsForServerSegment should not be called in cache contexts.'
)
case 'prerender-runtime':
return createRuntimePrerenderParams(underlyingParams, workUnitStore)
return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
)
case 'request':
if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev`
......@@ -238,8 +270,14 @@ export function createPrerenderParamsForClientSegment(
function createStaticPrerenderParams(
underlyingParams: Params,
workStore: WorkStore,
prerenderStore: StaticPrerenderStore
prerenderStore: StaticPrerenderStore,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> {
const underlyingParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams
switch (prerenderStore.type) {
case 'prerender':
case 'prerender-client': {
......@@ -252,7 +290,7 @@ function createStaticPrerenderParams(
// we are in cacheComponents mode we encode this as a promise that never
// resolves.
return makeHangingParams(
underlyingParams,
underlyingParamsWithVarying,
workStore,
prerenderStore
)
......@@ -267,7 +305,7 @@ function createStaticPrerenderParams(
for (const key in underlyingParams) {
if (fallbackParams.has(key)) {
return makeErroringParams(
underlyingParams,
underlyingParamsWithVarying,
fallbackParams,
workStore,
prerenderStore
......@@ -283,16 +321,22 @@ function createStaticPrerenderParams(
prerenderStore satisfies never
}
return makeUntrackedParams(underlyingParams)
return makeUntrackedParams(underlyingParamsWithVarying)
}
function createRuntimePrerenderParams(
underlyingParams: Params,
workUnitStore: PrerenderStoreModernRuntime
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> {
const underlyingParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams
return delayUntilRuntimeStage(
workUnitStore,
makeUntrackedParams(underlyingParams)
makeUntrackedParams(underlyingParamsWithVarying)
)
}
......
......@@ -17,6 +17,7 @@ import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { ParamValue } from './params'
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { accumulateRootVaryParam } from '../app-render/vary-params'
/**
* Used for the compiler-generated `next/root-params` module.
......@@ -83,6 +84,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
workUnitStore satisfies never
}
}
accumulateRootVaryParam(paramName)
return Promise.resolve(workUnitStore.rootParams[paramName])
}
......@@ -148,6 +151,7 @@ function createPrerenderRootParamPromise(
}
// If the param is not a fallback param, we just return the statically available value.
accumulateRootVaryParam(paramName)
return Promise.resolve(underlyingParams[paramName])
}
......
import type { WorkStore } from '../app-render/work-async-storage.external'
import type { VaryParamsAccumulator } from '../app-render/vary-params'
import {
createVaryingSearchParams,
getMetadataVaryParamsAccumulator,
} from '../app-render/vary-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
......@@ -73,12 +78,22 @@ export function createSearchParamsFromClient(
}
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
export const createServerSearchParamsForMetadata =
createServerSearchParamsForServerPage
export function createServerSearchParamsForMetadata(
underlyingSearchParams: SearchParams,
workStore: WorkStore
): Promise<SearchParams> {
const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()
return createServerSearchParamsForServerPage(
underlyingSearchParams,
workStore,
metadataVaryParamsAccumulator
)
}
export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams,
workStore: WorkStore
workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<SearchParams> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
......@@ -97,7 +112,8 @@ export function createServerSearchParamsForServerPage(
case 'prerender-runtime':
return createRuntimePrerenderSearchParams(
underlyingSearchParams,
workUnitStore
workUnitStore,
varyParamsAccumulator
)
case 'request':
return createRenderSearchParams(
......@@ -181,11 +197,16 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams,
workUnitStore: PrerenderStoreModernRuntime
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<SearchParams> {
const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
: underlyingSearchParams
return delayUntilRuntimeStage(
workUnitStore,
makeUntrackedSearchParams(underlyingSearchParams)
makeUntrackedSearchParams(underlyingSearchParamsWithVarying)
)
}
......
......@@ -420,6 +420,7 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
})
let prospectiveResult
......@@ -516,6 +517,7 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
})
let responseHandled = false
......
......@@ -11,6 +11,8 @@ export type LoadingModuleData =
| [React.JSX.Element, React.ReactNode, React.ReactNode]
| null
import type { VaryParamsThenable } from './segment-cache/vary-params-decoding'
/** viewport metadata node */
export type HeadData = React.ReactNode
......@@ -194,16 +196,20 @@ export type CacheNodeSeedData = [
/** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
hasRuntimePrefetch: boolean,
/**
* The set of params that this segment's server-rendered output depends on.
* Used by the client cache to determine which entries can be reused across
* different param values.
* A thenable that resolves to the set of route params this segment accessed
* during server rendering. Used by the client router to determine cache key
* specificity - segments that only access certain params can be reused across
* navigations where unaccessed params change.
*
* - `null` means vary params were not tracked (conservative: assume all
* params vary)
* - Empty set means no params were accessed (segment is reusable for any
* param values)
* - null thenable: tracking was not enabled for this render (e.g., not a
* prerender). Treat conservatively - assume all params vary.
* - Thenable resolves to empty Set: segment accesses no params (e.g., client
* components, or server components that don't read params). Can be shared
* across all param values.
* - Thenable resolves to non-empty Set: segment depends on those params.
* Can only reuse when those specific params match.
*/
varyParams: Set<string> | null,
varyParams: VaryParamsThenable | null,
]
export type FlightDataSegment = [
......@@ -248,6 +254,10 @@ export type InitialRSCPayload = {
G: [React.ComponentType<any>, React.ReactNode | undefined]
/** prerendered */
S: boolean
/**
* headVaryParams - vary params for the head (metadata) of the response.
*/
h: VaryParamsThenable | null
}
// Response from `createFromFetch` for normal rendering
......@@ -264,6 +274,8 @@ export type NavigationFlightResponse = {
i: boolean
/** runtimePrefetch - [isPartial, staleTime]. Only present in runtime prefetch responses. */
rp?: [boolean, number]
/** headVaryParams */
h: VaryParamsThenable | null
}
// Response from `createFromFetch` for server actions. Action's flight data can be null
......
/**
* Vary Params Decoding
*
* This module is shared between server and client.
*/
export type VaryParams = Set<string>
type FulfilledVaryParamsThenable = {
status: 'fulfilled'
value: VaryParams
} & PromiseLike<VaryParams>
type PendingVaryParamsThenable = {
// 'resolved_model' is an internal React Flight state: the underlying model
// data has arrived but the thenable hasn't been "unwrapped" yet. Calling
// .then() triggers Flight to synchronously transition to 'fulfilled'.
status: 'pending' | 'resolved_model'
value: unknown
} & PromiseLike<VaryParams>
export type VaryParamsThenable =
| FulfilledVaryParamsThenable
| PendingVaryParamsThenable
/**
* Synchronously reads vary params from a thenable.
*
* By the time this is called (client-side or in collectSegmentData), the
* thenable should already be fulfilled because the Flight stream has been
* fully received. We check the status synchronously to avoid unnecessary
* microtasks.
*
* Returns null if the thenable is still pending (which shouldn't happen in
* normal operation - it indicates the server failed to track vary params).
*/
export function readVaryParams(
thenable: VaryParamsThenable
): VaryParams | null {
// Attach a no-op listener to force Flight to synchronously resolve the
// thenable. When a thenable arrives from the Flight stream, it may be in an
// intermediate 'resolved_model' state (data received but not unwrapped).
// Calling .then() triggers Flight to transition it to 'fulfilled', making
// the value available synchronously. React uses this same optimization
// internally to avoid unnecessary microtasks.
thenable.then(noop)
// If the thenable is still not 'fulfilled' after calling .then(), the server
// failed to resolve it before the stream ended. Treat as unknown.
if (thenable.status !== 'fulfilled') {
return null
}
return thenable.value
}
const noop = () => {}
/**
* Loading boundary for the instant loading test. This component renders
* while the dynamic page content is loading.
*
* When the layout segment is cached (because category matches a previous
* prefetch), this loading state renders instantly from cache during
* navigation — no network round-trip required.
*/
export default function Loading() {
return <div data-loading="true">Loading item...</div>
}
type Params = { category: string; itemId: string }
/**
* Page component that renders the itemId param. This segment has NO
* generateStaticParams, so itemId is fully dynamic and loads behind
* the Suspense boundary (loading.tsx).
*
* When navigating to this page:
* 1. The parent [category] layout renders instantly from cache (it's static)
* 2. The loading.tsx shows while this page loads dynamically
* 3. This page replaces the loading state once the dynamic request completes
*/
export default async function InstantLoadingPage({
params,
}: {
params: Promise<Params>
}) {
const { category, itemId } = await params
return (
<div id="instant-loading-page">
<div data-category={category} data-item-id={itemId}>
Item: {itemId} (in category: {category})
</div>
</div>
)
}
type Params = { category: string }
/**
* Layout for the [category] segment. This layout:
* - Accesses only 'category' param → cached across different itemIds
* - Has generateStaticParams for 'electronics' → this segment is static
*
* The child [itemId] segment is dynamic (no generateStaticParams), so when
* navigating to different itemIds within the same category, this layout
* renders instantly from cache while the page loads dynamically.
*/
export async function generateStaticParams(): Promise<Params[]> {
return [{ category: 'electronics' }]
}
export default async function InstantLoadingCategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<Params>
}) {
const { category } = await params
return (
<div data-instant-loading-layout="true">
<div data-layout-category={category}>{`Category: ${category}`}</div>
{children}
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the instant loading state test. This is the canonical test
* for the vary params feature — it demonstrates the core user-facing benefit:
* instant loading feedback when navigating to routes that share cached segments.
*
* All links share category='electronics' but have different itemId values.
* Since the layout only accesses 'category', the layout segment is cached after
* the first prefetch and reused for all subsequent links.
*
* The page component renders itemId dynamically (not in generateStaticParams),
* so when navigating, the cached layout/loading shell renders instantly while
* the dynamic page content loads in the background.
*
* Manual testing:
* 1. Click the checkbox for "phone" — triggers prefetch, layout is fetched
* 2. Click the checkbox for "tablet" — cache hit, no request
* 3. Click the checkbox for "laptop" — cache hit, no request
* 4. Click the "headphones" link to navigate — loading state appears instantly
*/
export default function InstantLoadingIndexPage() {
return (
<div id="instant-loading-index">
<h1>Instant Loading State Test</h1>
<p>
Verifies that cached segments render instantly during navigation, even
when dynamic content hasn&apos;t loaded yet.
</p>
<ul>
<li>
<LinkAccordion href="/instant-loading/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/instant-loading/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/instant-loading/electronics/laptop">
Electronics: Laptop
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/instant-loading/electronics/headphones">
Electronics: Headphones
</LinkAccordion>
</li>
</ul>
</div>
)
}
/**
* Loading boundary for the metadata-no-params vary params test.
*/
export default function Loading() {
return <div data-loading="true">Loading page...</div>
}
type Params = { slug: string }
/**
* Page with generateMetadata that does NOT access params.
*
* This tests that when metadata doesn't access params, the head segment
* can be cached and reused across different param values.
*/
export async function generateStaticParams(): Promise<Params[]> {
return [{ slug: 'aaa' }, { slug: 'bbb' }]
}
export async function generateMetadata() {
// Intentionally NOT accessing params here
return { title: 'Static Title' }
}
export default function MetadataNoParamsPage() {
return (
<div id="metadata-no-params-page">
<div data-content="true">Page content (params not accessed)</div>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the metadata-no-params vary params test.
*
* This is the inverse of the metadata test: generateMetadata does NOT access
* params, so the head segment should be cacheable across different param values.
*
* Setup:
* - [slug]/page.tsx has generateMetadata that does NOT access params
* - The page body does NOT access params either
* - Links go to /metadata-no-params/aaa, /metadata-no-params/bbb
*
* Expected behavior:
* - First prefetch fetches head and body segments
* - Subsequent prefetches with different slugs are cache hits
* (neither metadata nor body access params)
*
* Manual testing:
* 1. Click checkbox for "aaa" - triggers prefetch, content fetched
* 2. Click checkbox for "bbb" - cache hit, no new request
*/
export default function MetadataNoParamsIndexPage() {
return (
<div id="metadata-no-params-index">
<h1>Metadata No Params Test</h1>
<p>
Tests that when generateMetadata does NOT access params, the head
segment can be cached across different param values.
</p>
<ul>
<li>
<LinkAccordion href="/metadata-no-params/aaa">
Slug: aaa
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/metadata-no-params/bbb">
Slug: bbb
</LinkAccordion>
</li>
</ul>
</div>
)
}
/**
* Loading boundary for the metadata vary params test.
*/
export default function Loading() {
return <div data-loading="true">Loading metadata page...</div>
}
type Params = { slug: string }
/**
* Page where generateMetadata accesses params but the body does NOT.
*
* This tests that metadata param access is tracked separately from page body.
* When the slug changes:
* - Head segment should be re-fetched (metadata accesses slug)
* - Body segment should be cached (body does NOT access slug)
*/
export async function generateStaticParams(): Promise<Params[]> {
return [{ slug: 'aaa' }, { slug: 'bbb' }, { slug: 'ccc' }]
}
export async function generateMetadata({
params,
}: {
params: Promise<Params>
}) {
const { slug } = await params
return { title: `Page: ${slug}` }
}
export default function MetadataPage() {
// Intentionally NOT accessing params here - body should be cached
return (
<div id="metadata-page">
<div data-content="true">{`Static page body`}</div>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the metadata vary params test.
*
* This tests that param access in generateMetadata is tracked in the head
* segment's varyParams, separate from body segment tracking.
*
* Setup:
* - [slug]/page.tsx has generateMetadata that accesses params
* - The page body does NOT access params
* - Links go to /metadata/aaa, /metadata/bbb, /metadata/ccc
*
* Expected behavior:
* - First prefetch fetches the head segment (varies on slug)
* - Subsequent prefetches with different slugs require new fetches
* because metadata accesses the slug param
*
* Manual testing:
* 1. Click checkbox for "aaa" - triggers prefetch, content fetched
* 2. Click checkbox for "bbb" - cache miss, new prefetch (slug changed)
* 3. Click checkbox for "ccc" - cache miss, new prefetch (slug changed)
*/
export default function MetadataIndexPage() {
return (
<div id="metadata-index">
<h1>Metadata Vary Params Test</h1>
<p>
Tests that param access in generateMetadata is tracked in the head
segment&apos;s varyParams.
</p>
<ul>
<li>
<LinkAccordion href="/metadata/aaa">Slug: aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/metadata/bbb">Slug: bbb</LinkAccordion>
</li>
<li>
<LinkAccordion href="/metadata/ccc">Slug: ccc</LinkAccordion>
</li>
</ul>
</div>
)
}
type Params = { category: string; item: string }
/**
* Layout for the [category]/[item] segment. This layout:
* - Accesses BOTH 'category' AND 'item' → must be re-fetched when either changes
*
* This is the inverse of the typical pattern. Usually the layout accesses fewer
* params than the page, enabling layout reuse. Here, the layout accesses MORE
* params than the page, which means:
* - When `item` changes, the layout must be re-fetched
* - But the page (which only accesses `category`) can be reused
*
* This tests that param access is tracked at the segment level, not just at
* the route level.
*/
export async function generateStaticParams(): Promise<Params[]> {
return [
{ category: 'electronics', item: 'phone' },
{ category: 'electronics', item: 'tablet' },
]
}
export default async function PageReuseLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<Params>
}) {
const { category, item } = await params
return (
<div data-page-reuse-layout="true">
<div data-layout-info={`${category}/${item}`}>
{`Layout: ${category}/${item}`}
</div>
{children}
</div>
)
}
/**
* Loading boundary for the page reuse test.
*
* This shows while the page content is loading. In this test, the loading
* state itself can be cached (it doesn't access any params), so it renders
* instantly when navigating.
*/
export default function Loading() {
return <div data-loading="true">Loading page...</div>
}
type Params = { category: string; item: string }
/**
* Page component that accesses ONLY the `category` param, NOT `item`.
*
* This is the key to this test: even though the URL includes both params,
* this page only accesses `category`. Therefore:
* - When navigating between /electronics/phone and /electronics/tablet,
* this page segment is a cache hit (category unchanged)
*
* The layout accesses both params, so it must be re-fetched when `item`
* changes. This demonstrates that param access tracking is per-segment,
* allowing fine-grained cache reuse.
*/
export default async function PageReusePage({
params,
}: {
params: Promise<Params>
}) {
// NOTE: Only accessing `category`, NOT `item`
// This is intentional to demonstrate page reuse when item changes
const { category } = await params
return (
<div id="page-reuse-page">
<div data-page-category={category}>{`Page category: ${category}`}</div>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the page segment reuse test.
*
* This test demonstrates a non-obvious case: a page segment can be reused when
* it doesn't access a param that the layout DOES access. This is the inverse
* of the typical pattern where layouts are reused while pages vary.
*
* Setup:
* - Layout accesses BOTH `category` AND `item` → varies on both
* - Page accesses ONLY `category` → varies only on category
*
* When navigating between routes that share the same category but different
* items (e.g., /electronics/phone → /electronics/tablet), the layout must be
* re-fetched (it accesses `item`), but the page is a cache hit (it only
* accesses `category`, which hasn't changed).
*
* Manual testing:
* 1. Click checkbox for "phone" — layout and page both fetched
* 2. Click checkbox for "tablet" — layout re-fetched, page is cache hit
*/
export default function PageReuseIndexPage() {
return (
<div id="page-reuse-index">
<h1>Page Segment Reuse Test</h1>
<p>
Tests the inverse of typical layout reuse: the page segment can be
reused when it doesn&apos;t access a param that the layout does access.
</p>
<p>
<strong>Layout:</strong> accesses both category and item
<br />
<strong>Page:</strong> accesses only category
</p>
<ul>
<li>
<LinkAccordion href="/page-reuse/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/page-reuse/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the root params vary test.
*
* This page links to routes that use the rootParams() API from next/navigation.
* The target routes are at /aaa and /bbb which have their own root layout
* (no shared app/layout.tsx above them), making `rootParam` a true "root param".
*
* Setup:
* - /aaa and /bbb have layouts that call rootParams()
* - The rootParam value is accessed in both layout and page
*
* Expected behavior:
* - Prefetching /aaa fetches the content
* - Prefetching /bbb triggers a NEW request (not a cache hit)
* because rootParam is tracked in varyParams
*
* Manual testing:
* 1. Click checkbox for "aaa" — triggers prefetch, content fetched
* 2. Click checkbox for "bbb" — should also fetch (not cached)
*/
export default function RootParamsIndexPage() {
return (
<div id="root-params-index">
<h1>Root Params Vary Test</h1>
<p>
Tests that root param access via rootParams() API is tracked in
varyParams.
</p>
<ul>
<li>
<LinkAccordion href="/aaa">Root Param: aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/bbb">Root Param: bbb</LinkAccordion>
</li>
</ul>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Runtime prefetch page - canonical test for runtime prefetching.
*
* This is the runtime prefetch equivalent of the instant-loading test:
* - `category` is accessed in the static/cached portion → enables cache sharing
* - `itemId` is accessed only in the dynamic portion → not relevant for caching
*
* This allows cache reuse across different itemId values (same category),
* providing instant loading feedback when navigating.
*/
export const unstable_prefetch: {
mode: 'runtime'
samples: Array<{ params: { category: string; itemId: string } }>
} = {
mode: 'runtime',
samples: [
{ params: { category: 'electronics', itemId: 'phone' } },
{ params: { category: 'clothing', itemId: 'shirt' } },
],
}
type Params = { category: string; itemId: string }
export default async function RuntimePrefetchPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="runtime-prefetch-page">
{/* Outer Suspense: category is accessed here, included in prefetch */}
<Suspense fallback={<div>Loading page...</div>}>
<StaticContent params={params} />
</Suspense>
</div>
)
}
async function StaticContent({ params }: { params: Promise<Params> }) {
// Access category in the static/cached portion — enables cache sharing
const { category } = await params
return (
<>
<div data-static-content="true">
{`Static content - Category: ${category}`}
</div>
{/* Inner Suspense: itemId accessed after connection(), NOT in prefetch */}
<Suspense
fallback={<div data-loading="true">Loading item details...</div>}
>
<DynamicContent params={params} />
</Suspense>
</>
)
}
async function DynamicContent({ params }: { params: Promise<Params> }) {
// This makes the component dynamic — excluded from the prefetch
await connection()
// Access itemId only in the dynamic portion — always fetched at runtime
const { category, itemId } = await params
return (
<div data-dynamic-content="true">
{`Dynamic content - Item: ${itemId} (in ${category})`}
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the runtime prefetch vary params test.
*
* This tests vary params tracking with runtime prefetching enabled. Unlike
* static prefetching, runtime prefetching allows dynamic params to be rendered
* as part of the prefetch (rather than being omitted). This enables testing
* more specific combinations:
*
* - The page renders `category` in the static portion → tracked in varyParams
* - The page renders `itemId` in the dynamic portion → NOT tracked in varyParams
*
* Since `itemId` is only accessed in the dynamic section (inside Suspense after
* connection()), the page should only vary on `category`, allowing cache reuse
* across different itemId values.
*
* Manual testing:
* 1. Click checkbox for "phone" — triggers prefetch, page content fetched
* 2. Click checkbox for "tablet" and "laptop" — cache hits (same category)
* 3. Navigate to "headphones" — loading state instant, then dynamic content loads
*/
export default function RuntimePrefetchIndexPage() {
return (
<div id="runtime-prefetch-index">
<h1>Runtime Prefetch Vary Params Test</h1>
<p>
Tests vary params tracking with runtime prefetching. The page renders
category in the static portion and itemId in the dynamic portion.
</p>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/electronics/laptop">
Electronics: Laptop
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/electronics/headphones">
Electronics: Headphones
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/clothing/shirt">
Clothing: Shirt
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
/**
* Index page for the search params access tracking test.
*
* This tests that when a page accesses searchParams, separate cache entries
* are created for each unique search param value.
*
* Two sub-routes:
* - /search-params/target-page?foo=X - Page accesses searchParams, NO cache reuse
* - /search-params/static-target?foo=X - Page does NOT access searchParams, cache reuse
*
* Manual testing:
* 1. Click checkbox for "?foo=1" target link - triggers prefetch
* 2. Click checkbox for "?foo=2" target link - should trigger NEW prefetch (no cache)
* 3. Click checkbox for "?foo=1" static-target link - triggers prefetch
* 4. Click checkbox for "?foo=2" static-target link - should be cache hit
*/
export default function SearchParamsIndexPage() {
return (
<div id="search-params-index">
<h1>Search Params Access Tracking Test</h1>
<p>
Tests that accessing searchParams creates separate cache entries for
each unique search param value.
</p>
<h2>Target (accesses searchParams)</h2>
<ul>
<li>
<LinkAccordion href="/search-params/target-page?foo=1">
Target with foo=1
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/search-params/target-page?foo=2">
Target with foo=2
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/search-params/target-page?foo=3">
Target with foo=3
</LinkAccordion>
</li>
</ul>
<h2>Static Target (does not access searchParams)</h2>
<ul>
<li>
<LinkAccordion href="/search-params/static-target?foo=1">
Static target with foo=1
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/search-params/static-target?foo=2">
Static target with foo=2
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/search-params/static-target?foo=3">
Static target with foo=3
</LinkAccordion>
</li>
</ul>
</div>
)
}
/**
* Loading boundary for the static target page.
*/
export default function Loading() {
return <div data-loading="true">Loading static target...</div>
}
/**
* Page that does NOT access searchParams.
*
* This page renders static content without awaiting searchParams.
* Since '?' is NOT included in varyParams, different search param values
* WILL share cached prefetch data.
*
* Expected behavior:
* - Prefetching /static-target?foo=1 fetches the segment
* - Prefetching /static-target?foo=2 is a cache HIT (reuses first prefetch)
*/
export default async function StaticTargetPage() {
return (
<div id="static-target-page">
<div data-static-target-content="true">
{`Static target content - no searchParams access`}
</div>
</div>
)
}
/**
* Loading boundary for the search params target page.
*/
export default function Loading() {
return <div data-loading="true">Loading search params target...</div>
}
import { Suspense } from 'react'
/**
* Page that accesses searchParams with runtime prefetching.
*
* By awaiting searchParams, this page's cache key varies by search params.
* Different search param values will NOT share cached prefetch data.
*
* The searchParams access must be inside a Suspense boundary for runtime
* prefetching to work - the page shell is static, the searchParams-dependent
* content is runtime-prefetchable.
*
* Expected behavior:
* - Prefetching /target?foo=1 fetches the segment with foo=1 content
* - Prefetching /target?foo=2 fetches the segment AGAIN (no cache hit)
*/
export const unstable_prefetch = {
mode: 'runtime',
samples: [{ searchParams: { foo: '1' } }],
}
type SearchParams = { foo?: string }
export default async function SearchParamsTargetPage({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
return (
<div id="search-params-target-page">
<Suspense fallback={<div>Loading search params...</div>}>
<SearchParamsContent searchParams={searchParams} />
</Suspense>
</div>
)
}
async function SearchParamsContent({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
// Access searchParams inside Suspense - this affects the cache key
const { foo } = await searchParams
return (
<div data-search-params-content="true">
{`Search params target - foo: ${foo ?? 'undefined'}`}
</div>
)
}
import { rootParam } from 'next/root-params'
type Params = { rootParam: string }
/**
* Root layout for the root params test.
*
* This layout is the first layout in its route tree (no app/layout.tsx above it),
* which makes `rootParam` a "root param" accessible via `next/root-params`.
*
* The layout accesses rootParam via the next/root-params API to verify that
* root param access is properly tracked in varyParams.
*/
export async function generateStaticParams(): Promise<Params[]> {
return [{ rootParam: 'aaa' }, { rootParam: 'bbb' }]
}
export default async function RootParamsLayout({
children,
}: {
children: React.ReactNode
}) {
const param = await rootParam()
return (
<html>
<body>
<div data-root-params-layout="true">
<div data-root-param={param}>
{`Root param layout - param: ${param}`}
</div>
{children}
</div>
</body>
</html>
)
}
export default function Loading() {
return <div data-loading="true">Loading [param]...</div>
return <div data-loading="true">Loading root param page...</div>
}
import { rootParam } from 'next/root-params'
/**
* Page that accesses rootParam via the next/root-params API.
*
* This tests that root param access is tracked in varyParams. When accessing
* /aaa vs /bbb, each should trigger a separate prefetch because rootParam
* is accessed via next/root-params.
*/
export default async function RootParamsPage() {
const param = await rootParam()
return (
<div id="root-params-page">
<div data-root-param-content="true">
{`Root param page content - param: ${param}`}
</div>
</div>
)
}
'use client'
/**
* This is a client component layout. Even though it has access to params via
* the props, it doesn't access them on the server during rendering. This means
* the segment's varyParams should be an empty set, allowing the prefetched
* data to be reused across different param values.
*/
export default function ClientLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div data-client-layout="true">
<div>Client Layout (use client)</div>
{children}
</div>
)
}
export default function Loading() {
return <div data-loading="client-layout">Loading client layout...</div>
}
type Params = { param: string }
export async function generateStaticParams(): Promise<Params[]> {
return [{ param: 'aaa' }, { param: 'bbb' }]
}
export default async function Page({ params }: { params: Promise<Params> }) {
const { param } = await params
return (
<div id="client-layout-param-page">
<div data-param={param}>Param value: {param}</div>
</div>
)
}
import { LinkAccordion } from '../../components/link-accordion'
export default function ClientLayoutIndexPage() {
return (
<div id="client-layout-index">
<h1>Client Layout Index</h1>
<ul>
<li>
<LinkAccordion href="/client-layout/aaa">Link to aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/client-layout/bbb">Link to bbb</LinkAccordion>
</li>
</ul>
</div>
)
}
type Params = { param: string }
export async function generateStaticParams(): Promise<Params[]> {
return [{ param: 'aaa' }, { param: 'bbb' }]
}
export default async function Page({ params }: { params: Promise<Params> }) {
const { param } = await params
return (
<div id="param-page">
<div data-param={param}>Param value: {param}</div>
</div>
)
}
import { LinkAccordion } from '../../components/link-accordion'
export default function StaticPage() {
return (
<div id="index-page">
<h1>Index Page</h1>
<ul>
<li>
<LinkAccordion href="/static/aaa">Link to aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/static/bbb">Link to bbb</LinkAccordion>
</li>
</ul>
</div>
)
}
......@@ -3,6 +3,9 @@
*/
const nextConfig = {
cacheComponents: true,
experimental: {
optimisticRouting: true,
},
}
module.exports = nextConfig
......@@ -3,12 +3,20 @@ import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
/**
* Tests for the "vary params" optimization. Segments that don't access params
* on the server can have their prefetched data reused across different param
* values. This includes:
* Tests for the "vary params" optimization.
*
* 1. Segments without a user-provided layout (only loading.tsx or nothing)
* 2. Segments with a 'use client' layout (client components don't run on server)
* Background: During prerendering, Next.js tracks which params each segment
* actually accesses on the server. This enables the client cache to share
* entries: when a segment doesn't access a param, different values of that
* param can reuse the same cached segment.
*
* Core behavior under test:
* - When a segment accesses a param, changing that param requires a new prefetch
* - When a segment does NOT access a param, changing that param reuses the cache
*
* The first test (instant loading state) is the canonical demonstration of
* the feature's user-facing benefit. Subsequent tests exercise various
* combinations of features and edge cases.
*/
describe('segment cache - vary params', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -20,99 +28,345 @@ describe('segment cache - vary params', () => {
return
}
it('reuses prefetched segment when there is no user-provided layout', async () => {
it('renders cached loading state instantly during navigation', async () => {
// Setup: All links share category='electronics' but different itemId values.
// Layout only accesses 'category', page renders itemId dynamically.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/static', {
const browser = await next.browser('/instant-loading', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch the first link (/static/aaa). This will populate the segment
// cache with the [param] segment's loading boundary.
// Prefetch the first link - layout is fetched
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/instant-loading/electronics/phone"]'
)
await toggle.click()
},
{ includes: 'Category: electronics' }
)
// Prefetch remaining links - all cache hits (same category, layout cached)
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/static/aaa"]'
const tablet = await browser.elementByCss(
'input[data-link-accordion="/instant-loading/electronics/tablet"]'
)
await toggle.click()
await tablet.click()
const laptop = await browser.elementByCss(
'input[data-link-accordion="/instant-loading/electronics/laptop"]'
)
await laptop.click()
const headphones = await browser.elementByCss(
'input[data-link-accordion="/instant-loading/electronics/headphones"]'
)
await headphones.click()
}, 'no-requests')
// Navigate to headphones. The loading state renders synchronously from
// the cached layout, before the dynamic request resolves. The assertion
// runs inside act() during navigation, verifying it appears instantly.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/instant-loading/electronics/headphones"]'
)
await link.click()
const loading = await browser.elementByCss('[data-loading="true"]')
expect(await loading.text()).toContain('Loading item')
})
// Now prefetch the second link (/static/bbb). Because the [param] segment
// has no user-provided layout (only loading.tsx), its varyParams is an
// empty set. This means the segment data from /static/aaa is re-keyed with
// Fallback and should be reused for /static/bbb.
//
// We should NOT see a new prefetch request for the [param] segment's
// loading boundary - only the page content should be fetched.
// Dynamic content eventually loads
const page = await browser.elementById('instant-loading-page')
expect(await page.text()).toContain('Item: headphones')
})
// TODO: Re-enable once vary params tracking is implemented for runtime
// prefetch abort paths. The abort timing needs to resolve vary params before
// the abort signal fires. See static-siblings-infrastructure branch.
it.skip('renders cached loading state instantly with runtime prefetching', async () => {
// Setup: Page accesses `category` in static portion (tracked in varyParams),
// but accesses `itemId` only after connection() (not tracked).
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch first link - static content fetched
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch/electronics/phone"]'
)
await toggle.click()
},
{ includes: 'Static content - Category: electronics' }
)
// Prefetch remaining links with same category - all cache hits
await act(async () => {
const tablet = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch/electronics/tablet"]'
)
await tablet.click()
const laptop = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch/electronics/laptop"]'
)
await laptop.click()
const headphones = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch/electronics/headphones"]'
)
await headphones.click()
}, 'no-requests')
// Prefetch link with different category - triggers new prefetch
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/static/bbb"]'
'input[data-link-accordion="/runtime-prefetch/clothing/shirt"]'
)
await toggle.click()
},
// The loading boundary content should NOT be re-fetched because the
// segment shell is reused from the /static/aaa prefetch.
{ includes: 'Loading [param]', block: 'reject' }
{ includes: 'Static content - Category: clothing' }
)
// Navigate to /static/bbb and verify it works. Since all the data is
// prefetched, there should be no additional requests during navigation.
// Navigate to headphones. Loading state renders synchronously from cache.
await act(async () => {
const link = await browser.elementByCss('a[href="/static/bbb"]')
const link = await browser.elementByCss(
'a[href="/runtime-prefetch/electronics/headphones"]'
)
await link.click()
const loading = await browser.elementByCss('[data-loading="true"]')
expect(await loading.text()).toContain('Loading item details')
})
// Dynamic content eventually loads
const dynamicContent = await browser.elementByCss('[data-dynamic-content]')
expect(await dynamicContent.text()).toContain('Item: headphones')
})
it('does not reuse prefetched segment when page accesses searchParams', async () => {
// When a page awaits searchParams, the cache key includes the search
// params, so different values require separate prefetches.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Each prefetch triggers a new request (not cached)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?foo=1"]'
)
await toggle.click()
},
{ includes: 'Search params target - foo: 1' }
)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?foo=2"]'
)
await toggle.click()
},
{ includes: 'Search params target - foo: 2' }
)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?foo=3"]'
)
await toggle.click()
},
{ includes: 'Search params target - foo: 3' }
)
})
it('reuses prefetched segment when page does not access searchParams', async () => {
// When a page does NOT await searchParams, the cache key does NOT include
// search params, so different values share cached prefetch data.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches the segment
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/static-target?foo=1"]'
)
await toggle.click()
},
{ includes: 'Static target content - no searchParams access' }
)
// Subsequent prefetches are cache hits
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/static-target?foo=2"]'
)
await toggle.click()
}, 'no-requests')
// Verify the final page content
const paramPage = await browser.elementById('param-page')
expect(await paramPage.text()).toContain('Param value: bbb')
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/search-params/static-target?foo=3"]'
)
await toggle.click()
}, 'no-requests')
})
it("reuses prefetched segment when layout is marked with 'use client'", async () => {
it('tracks param access in generateMetadata', async () => {
// Setup: generateMetadata accesses params, but the page body does NOT.
// This tests that metadata param access is tracked separately.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/client-layout', {
const browser = await next.browser('/metadata', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch the first link (/client-layout/aaa). This will populate the
// segment cache with the [param] segment's client layout.
// First prefetch fetches both head and body
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/metadata/aaa"]'
)
await toggle.click()
}, [{ includes: 'Page: aaa' }, { includes: 'Static page body' }])
// Second prefetch: head re-fetched (metadata varies on slug),
// but body is cached (body doesn't access slug)
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/client-layout/aaa"]'
'input[data-link-accordion="/metadata/bbb"]'
)
await toggle.click()
}, [
{ includes: 'Page: bbb' },
{ includes: 'Static page body', block: 'reject' },
])
})
it('caches head segment when generateMetadata does not access params', async () => {
// When neither generateMetadata nor the page body access params,
// both head and body are cached across different param values.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/metadata-no-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Now prefetch the second link (/client-layout/bbb). Because the [param]
// segment has a 'use client' layout, it doesn't access params on the
// server, so its varyParams is an empty set. The segment data from
// /client-layout/aaa should be reused for /client-layout/bbb.
//
// We should NOT see a new prefetch request for the [param] segment's
// layout - only the page content should be fetched.
// First prefetch fetches content
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/client-layout/bbb"]'
'input[data-link-accordion="/metadata-no-params/aaa"]'
)
await toggle.click()
},
// The client layout content should NOT be re-fetched because the segment
// is reused from the /client-layout/aaa prefetch.
{ includes: 'Client Layout (use client)', block: 'reject' }
{ includes: 'Page content' }
)
// Navigate to /client-layout/bbb and verify it works. Since all the data
// is prefetched, there should be no additional requests during navigation.
// Second prefetch is a cache hit
await act(async () => {
const link = await browser.elementByCss('a[href="/client-layout/bbb"]')
await link.click()
const toggle = await browser.elementByCss(
'input[data-link-accordion="/metadata-no-params/bbb"]'
)
await toggle.click()
}, 'no-requests')
})
it('reuses page segment when layout varies but page does not', async () => {
// Setup: Layout accesses both `category` and `item`, page only accesses
// `category`. When item changes but category stays the same, the layout
// must be re-fetched but the page is cached.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/page-reuse', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches both layout and page
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/page-reuse/electronics/phone"]'
)
await toggle.click()
}, [
{ includes: 'Layout: electronics/phone' },
{ includes: 'Page category:' },
])
// Second prefetch: layout re-fetched (varies on item),
// page is cached (only varies on category)
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/page-reuse/electronics/tablet"]'
)
await toggle.click()
}, [
{ includes: 'Layout: electronics/tablet' },
{ includes: 'Page category:', block: 'reject' },
])
// Navigate to verify cached page content renders correctly
const link = await browser.elementByCss(
'a[href="/page-reuse/electronics/tablet"]'
)
await link.click()
const layout = await browser.elementByCss('[data-page-reuse-layout]')
expect(await layout.text()).toContain('Layout: electronics/tablet')
const page = await browser.elementById('page-reuse-page')
expect(await page.text()).toContain('Page category: electronics')
})
it('tracks root param access via rootParams API', async () => {
// Root params accessed via rootParams() are tracked in varyParams.
// Different param values require separate prefetches.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/root-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches content
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/aaa"]'
)
await toggle.click()
},
{ includes: 'Root param page content - param: aaa' }
)
// Verify the final page content
const paramPage = await browser.elementById('client-layout-param-page')
expect(await paramPage.text()).toContain('Param value: bbb')
// Second prefetch triggers new fetch (not cached)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/bbb"]'
)
await toggle.click()
},
{ includes: 'Root param page content - param: bbb' }
)
})
})
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