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 { ...@@ -7,6 +7,10 @@ import type {
CacheNodeSeedData, CacheNodeSeedData,
Segment as FlightRouterStateSegment, Segment as FlightRouterStateSegment,
} from '../../../shared/lib/app-router-types' } 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 { HasLoadingBoundary } from '../../../shared/lib/app-router-types'
import { import {
NEXT_DID_POSTPONE_HEADER, NEXT_DID_POSTPONE_HEADER,
...@@ -1756,6 +1760,13 @@ export async function fetchRouteOnCacheMiss( ...@@ -1756,6 +1760,13 @@ export async function fetchRouteOnCacheMiss(
return null 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( writeDynamicTreeResponseIntoCache(
Date.now(), Date.now(),
task, task,
...@@ -1768,6 +1779,7 @@ export async function fetchRouteOnCacheMiss( ...@@ -1768,6 +1779,7 @@ export async function fetchRouteOnCacheMiss(
couldBeIntercepted, couldBeIntercepted,
canonicalUrl, canonicalUrl,
routeIsPPREnabled, routeIsPPREnabled,
headVaryParams,
pathname pathname
) )
} }
...@@ -2049,6 +2061,13 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2049,6 +2061,13 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
: // Full and LoadingBoundary prefetches cannot have holes. : // 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) // (even if we did set the prefetch header, we only use this codepath for non-PPR-enabled routes)
false 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 // Aside from writing the data into the cache, this function also returns
// the entries that were fulfilled, so we can streamingly update their sizes // the entries that were fulfilled, so we can streamingly update their sizes
...@@ -2060,6 +2079,7 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2060,6 +2079,7 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
response as RSCResponse<NavigationFlightResponse>, response as RSCResponse<NavigationFlightResponse>,
serverData, serverData,
isResponsePartial, isResponsePartial,
headVaryParams,
route, route,
spawnedEntries spawnedEntries
) )
...@@ -2086,8 +2106,9 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2086,8 +2106,9 @@ function writeDynamicTreeResponseIntoCache(
couldBeIntercepted: boolean, couldBeIntercepted: boolean,
canonicalUrl: string, canonicalUrl: string,
routeIsPPREnabled: boolean, routeIsPPREnabled: boolean,
headVaryParams: VaryParams | null,
originalPathname: string originalPathname: string
) { ): void {
const renderedSearch = getRenderedSearch(response) const renderedSearch = getRenderedSearch(response)
const normalizedFlightDataResult = normalizeFlightData(serverData.f) const normalizedFlightDataResult = normalizeFlightData(serverData.f)
...@@ -2160,6 +2181,7 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2160,6 +2181,7 @@ function writeDynamicTreeResponseIntoCache(
response, response,
serverData, serverData,
isResponsePartial, isResponsePartial,
headVaryParams,
fulfilledEntry, fulfilledEntry,
null null
) )
...@@ -2190,6 +2212,7 @@ function writeDynamicRenderResponseIntoCache( ...@@ -2190,6 +2212,7 @@ function writeDynamicRenderResponseIntoCache(
response: RSCResponse<NavigationFlightResponse>, response: RSCResponse<NavigationFlightResponse>,
serverData: NavigationFlightResponse, serverData: NavigationFlightResponse,
isResponsePartial: boolean, isResponsePartial: boolean,
headVaryParams: VaryParams | null,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
): Array<FulfilledSegmentCacheEntry> | null { ): Array<FulfilledSegmentCacheEntry> | null {
...@@ -2261,12 +2284,14 @@ function writeDynamicRenderResponseIntoCache( ...@@ -2261,12 +2284,14 @@ function writeDynamicRenderResponseIntoCache(
const head = flightData.head const head = flightData.head
if (head !== null) { if (head !== null) {
// For head entries, use the head-specific vary params passed as parameter.
fulfillEntrySpawnedByRuntimePrefetch( fulfillEntrySpawnedByRuntimePrefetch(
now, now,
fetchStrategy, fetchStrategy,
head, head,
flightData.isHeadPartial, flightData.isHeadPartial,
staleAt, staleAt,
headVaryParams,
route.metadata, route.metadata,
spawnedEntries spawnedEntries
) )
...@@ -2310,12 +2335,19 @@ function writeSeedDataIntoCache( ...@@ -2310,12 +2335,19 @@ function writeSeedDataIntoCache(
// (CacheNodeSeedData) into the prefetch cache. // (CacheNodeSeedData) into the prefetch cache.
const rsc = seedData[0] const rsc = seedData[0]
const isPartial = rsc === null || isResponsePartial 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( fulfillEntrySpawnedByRuntimePrefetch(
now, now,
fetchStrategy, fetchStrategy,
rsc, rsc,
isPartial, isPartial,
staleAt, staleAt,
varyParams,
tree, tree,
entriesOwnedByCurrentTask entriesOwnedByCurrentTask
) )
...@@ -2353,6 +2385,7 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -2353,6 +2385,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
rsc: React.ReactNode, rsc: React.ReactNode,
isPartial: boolean, isPartial: boolean,
staleAt: number, staleAt: number,
segmentVaryParams: Set<string> | null,
tree: RouteTree, tree: RouteTree,
entriesOwnedByCurrentTask: Map< entriesOwnedByCurrentTask: Map<
SegmentRequestKey, SegmentRequestKey,
...@@ -2367,7 +2400,26 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -2367,7 +2400,26 @@ function fulfillEntrySpawnedByRuntimePrefetch(
? entriesOwnedByCurrentTask.get(tree.requestKey) ? entriesOwnedByCurrentTask.get(tree.requestKey)
: undefined : undefined
if (ownedEntry !== 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 { } else {
// There's no matching entry. Attempt to create a new one. // There's no matching entry. Attempt to create a new one.
const possiblyNewEntry = readOrCreateSegmentCacheEntry( const possiblyNewEntry = readOrCreateSegmentCacheEntry(
...@@ -2378,12 +2430,26 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -2378,12 +2430,26 @@ function fulfillEntrySpawnedByRuntimePrefetch(
if (possiblyNewEntry.status === EntryStatus.Empty) { if (possiblyNewEntry.status === EntryStatus.Empty) {
// Confirmed this is a new entry. We can fulfill it. // Confirmed this is a new entry. We can fulfill it.
const newEntry = possiblyNewEntry const newEntry = possiblyNewEntry
fulfillSegmentCacheEntry( const fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(newEntry, fetchStrategy), upgradeToPendingSegment(newEntry, fetchStrategy),
rsc, rsc,
staleAt, staleAt,
isPartial 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 { } else {
// There was already an entry in the cache. But we may be able to // There was already an entry in the cache. But we may be able to
// replace it with the new one from the server. // replace it with the new one from the server.
...@@ -2396,11 +2462,13 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -2396,11 +2462,13 @@ function fulfillEntrySpawnedByRuntimePrefetch(
staleAt, staleAt,
isPartial isPartial
) )
upsertSegmentEntry( // Use the fulfilled vary path if available, otherwise fall back to
now, // the request vary path.
getSegmentVaryPathForRequest(fetchStrategy, tree), const varyPath =
newEntry segmentVaryParams !== null
) ? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams)
: getSegmentVaryPathForRequest(fetchStrategy, tree)
upsertSegmentEntry(now, varyPath, newEntry)
} }
} }
} }
......
...@@ -119,6 +119,7 @@ export function createInitialRSCPayloadFromFallbackPrerender( ...@@ -119,6 +119,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
m: fallbackInitialRSCPayload.m, m: fallbackInitialRSCPayload.m,
G: fallbackInitialRSCPayload.G, G: fallbackInitialRSCPayload.G,
S: fallbackInitialRSCPayload.S, S: fallbackInitialRSCPayload.S,
h: fallbackInitialRSCPayload.h,
} }
} }
......
...@@ -179,6 +179,11 @@ import { ...@@ -179,6 +179,11 @@ import {
} from './work-unit-async-storage.external' } from './work-unit-async-storage.external'
import { consoleAsyncStorage } from './console-async-storage.external' import { consoleAsyncStorage } from './console-async-storage.external'
import { CacheSignal } from './cache-signal' import { CacheSignal } from './cache-signal'
import {
createResponseVaryParamsAccumulator,
finishAccumulatingVaryParams,
getMetadataVaryParamsThenable,
} from './vary-params'
import { getTracedMetadata } from '../lib/trace/utils' import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
...@@ -564,6 +569,7 @@ async function generateDynamicRSCPayload( ...@@ -564,6 +569,7 @@ async function generateDynamicRSCPayload(
q: getRenderedSearch(query), q: getRenderedSearch(query),
i: !!couldBeIntercepted, i: !!couldBeIntercepted,
S: workStore.isStaticGeneration, S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
} }
// For runtime prefetches, we encode the stale time and isPartial flag in the response body // For runtime prefetches, we encode the stale time and isPartial flag in the response body
...@@ -1052,6 +1058,8 @@ async function prospectiveRuntimeServerPrerender( ...@@ -1052,6 +1058,8 @@ async function prospectiveRuntimeServerPrerender(
renderResumeDataCache, renderResumeDataCache,
prerenderResumeDataCache, prerenderResumeDataCache,
hmrRefreshHash: undefined, 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. // We only need task sequencing in the final prerender.
runtimeStagePromise: null, runtimeStagePromise: null,
// These are not present in regular prerenders, but allowed in a runtime prerender. // These are not present in regular prerenders, but allowed in a runtime prerender.
...@@ -1298,6 +1306,8 @@ async function finalRuntimeServerPrerender( ...@@ -1298,6 +1306,8 @@ async function finalRuntimeServerPrerender(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// TODO: Enable vary params tracking for runtime prefetches.
varyParamsAccumulator: null,
// Used to separate the "Static" stage from the "Runtime" stage. // Used to separate the "Static" stage from the "Runtime" stage.
runtimeStagePromise, runtimeStagePromise,
// These are not present in regular prerenders, but allowed in a runtime prerender. // These are not present in regular prerenders, but allowed in a runtime prerender.
...@@ -1554,6 +1564,7 @@ async function getRSCPayload( ...@@ -1554,6 +1564,7 @@ async function getRSCPayload(
m: missingSlots, m: missingSlots,
G: [GlobalError, globalErrorStyles], G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration, S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
} }
} }
...@@ -1679,6 +1690,7 @@ async function getErrorRSCPayload( ...@@ -1679,6 +1690,7 @@ async function getErrorRSCPayload(
], ],
G: [GlobalError, globalErrorStyles], G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration, S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
} satisfies InitialRSCPayload } satisfies InitialRSCPayload
} }
...@@ -3817,6 +3829,8 @@ async function warmupModuleCacheForRuntimeValidationInDev( ...@@ -3817,6 +3829,8 @@ async function warmupModuleCacheForRuntimeValidationInDev(
prerenderResumeDataCache: null, prerenderResumeDataCache: null,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
} }
const runtimeServerStream = createNodeStreamFromChunks( const runtimeServerStream = createNodeStreamFromChunks(
...@@ -3960,6 +3974,8 @@ async function validateStagedShell( ...@@ -3960,6 +3974,8 @@ async function validateStagedShell(
prerenderResumeDataCache: null, prerenderResumeDataCache: null,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
} }
let runtimeDynamicValidation = createDynamicValidationState() let runtimeDynamicValidation = createDynamicValidationState()
...@@ -4319,6 +4335,8 @@ async function prerenderToStream( ...@@ -4319,6 +4335,8 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, 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 // 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( ...@@ -4352,6 +4370,8 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null,
}) })
const pendingInitialServerResult = workUnitAsyncStorage.run( const pendingInitialServerResult = workUnitAsyncStorage.run(
...@@ -4471,6 +4491,8 @@ async function prerenderToStream( ...@@ -4471,6 +4491,8 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
} }
const prerender = ( const prerender = (
...@@ -4571,6 +4593,8 @@ async function prerenderToStream( ...@@ -4571,6 +4593,8 @@ async function prerenderToStream(
const finalServerReactController = new AbortController() const finalServerReactController = new AbortController()
const finalServerRenderController = new AbortController() const finalServerRenderController = new AbortController()
const varyParamsAccumulator = createResponseVaryParamsAccumulator()
const finalServerPayloadPrerenderStore: PrerenderStore = { const finalServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
phase: 'render', phase: 'render',
...@@ -4595,6 +4619,7 @@ async function prerenderToStream( ...@@ -4595,6 +4619,7 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator,
} }
const finalAttemptRSCPayload = await workUnitAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
...@@ -4629,6 +4654,7 @@ async function prerenderToStream( ...@@ -4629,6 +4654,7 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator,
}) })
let prerenderIsPending = true let prerenderIsPending = true
...@@ -4669,7 +4695,20 @@ async function prerenderToStream( ...@@ -4669,7 +4695,20 @@ async function prerenderToStream(
return prerenderResult 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 (finalServerReactController.signal.aborted) {
// If the server controller is already aborted we must have called something // If the server controller is already aborted we must have called something
// that required aborting the prerender synchronously such as with new Date() // that required aborting the prerender synchronously such as with new Date()
...@@ -4714,6 +4753,8 @@ async function prerenderToStream( ...@@ -4714,6 +4753,8 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
} }
let dynamicValidation = createDynamicValidationState() let dynamicValidation = createDynamicValidationState()
......
...@@ -6,6 +6,7 @@ import type { ...@@ -6,6 +6,7 @@ import type {
DynamicParamTypesShort, DynamicParamTypesShort,
HeadData, HeadData,
} from '../../shared/lib/app-router-types' } 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' import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -245,6 +246,15 @@ async function PrefetchTreeData({ ...@@ -245,6 +246,15 @@ async function PrefetchTreeData({
const seedData: CacheNodeSeedData = flightDataPaths[0][1] const seedData: CacheNodeSeedData = flightDataPaths[0][1]
const head: HeadData = flightDataPaths[0][2] 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 // 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 // walk the tree, we will also spawn a task to produce a prefetch response for
// each segment. // each segment.
...@@ -270,9 +280,7 @@ async function PrefetchTreeData({ ...@@ -270,9 +280,7 @@ async function PrefetchTreeData({
staleTime, staleTime,
head, head,
HEAD_REQUEST_KEY, HEAD_REQUEST_KEY,
// TODO: Track vary params for metadata. For now, assume all headVaryParams,
// params vary.
null,
clientModules clientModules
) )
) )
...@@ -336,7 +344,15 @@ function collectSegmentDataImpl( ...@@ -336,7 +344,15 @@ function collectSegmentDataImpl(
} }
const hasRuntimePrefetch = seedData !== null ? seedData[4] : false 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) { if (seedData !== null) {
// Spawn a task to write the segment data to a new Flight stream. // Spawn a task to write the segment data to a new Flight stream.
......
...@@ -23,6 +23,12 @@ import { NextNodeServerSpan } from '../lib/trace/constants' ...@@ -23,6 +23,12 @@ import { NextNodeServerSpan } from '../lib/trace/constants'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import type { Params } from '../request/params' import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external' import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import {
createVaryParamsAccumulator,
emptyVaryParamsAccumulator,
getVaryParamsThenable,
type VaryParamsAccumulator,
} from './vary-params'
import type { import type {
UseCacheLayoutProps, UseCacheLayoutProps,
UseCachePageProps, UseCachePageProps,
...@@ -672,8 +678,6 @@ async function createComponentTreeInternal( ...@@ -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 // 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) { if (!MaybeComponent) {
// No user-provided component at this level, so no params are accessed.
const emptyVaryParams = new Set<string>()
return createSeedData( return createSeedData(
ctx, ctx,
createElement( createElement(
...@@ -688,7 +692,9 @@ async function createComponentTreeInternal( ...@@ -688,7 +692,9 @@ async function createComponentTreeInternal(
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch, 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( ...@@ -709,8 +715,6 @@ async function createComponentTreeInternal(
workStore.forceDynamic && workStore.forceDynamic &&
experimental.isRoutePPREnabled experimental.isRoutePPREnabled
) { ) {
// force-dynamic segments can't have their vary params tracked
const unknownVaryParams = null
return createSeedData( return createSeedData(
ctx, ctx,
createElement( createElement(
...@@ -728,21 +732,20 @@ async function createComponentTreeInternal( ...@@ -728,21 +732,20 @@ async function createComponentTreeInternal(
loadingData, loadingData,
true, true,
hasRuntimePrefetch, 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 isClientComponent = isClientReference(layoutOrPageMod)
const varyParams = const varyParamsAccumulator =
isClientComponent && cacheComponents isClientComponent && cacheComponents
? // Client components with Cache Components enabled don't receive params ? // Client components with Cache Components enabled don't receive params
// from the server, so they have an empty vary params set. // from the server, so they have an empty vary params set.
new Set<string>() emptyVaryParamsAccumulator
: // TODO: Server segments don't yet track which params are accessed. : createVaryParamsAccumulator()
// So for now we must assume that all params may vary (null represents
// unknown vary params, not an empty set).
null
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
...@@ -794,13 +797,18 @@ async function createComponentTreeInternal( ...@@ -794,13 +797,18 @@ async function createComponentTreeInternal(
// their usage in case the current render mode tracks dynamic API usage. // their usage in case the current render mode tracks dynamic API usage.
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
workStore workStore,
varyParamsAccumulator
) )
// If we are passing searchParams to a server component Page we need to // 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 // track their usage in case the current render mode tracks dynamic API
// usage. // usage.
let searchParams = createServerSearchParamsForServerPage(query, workStore) let searchParams = createServerSearchParamsForServerPage(
query,
workStore,
varyParamsAccumulator
)
if (isUseCacheFunction(PageComponent)) { if (isUseCacheFunction(PageComponent)) {
const UseCachePageComponent: ComponentType<UseCachePageProps> = const UseCachePageComponent: ComponentType<UseCachePageProps> =
...@@ -852,7 +860,7 @@ async function createComponentTreeInternal( ...@@ -852,7 +860,7 @@ async function createComponentTreeInternal(
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch, hasRuntimePrefetch,
varyParams varyParamsAccumulator
) )
} else { } else {
const SegmentComponent = Component const SegmentComponent = Component
...@@ -970,7 +978,8 @@ async function createComponentTreeInternal( ...@@ -970,7 +978,8 @@ async function createComponentTreeInternal(
} else { } else {
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
workStore workStore,
varyParamsAccumulator
) )
let serverSegment: React.ReactNode let serverSegment: React.ReactNode
...@@ -1066,7 +1075,7 @@ async function createComponentTreeInternal( ...@@ -1066,7 +1075,7 @@ async function createComponentTreeInternal(
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch, hasRuntimePrefetch,
varyParams varyParamsAccumulator
) )
} }
} }
...@@ -1218,7 +1227,7 @@ function createSeedData( ...@@ -1218,7 +1227,7 @@ function createSeedData(
loading: LoadingModuleData | null, loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean, isPossiblyPartialResponse: boolean,
hasRuntimePrefetch: boolean, hasRuntimePrefetch: boolean,
varyParams: Set<string> | null varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData { ): CacheNodeSeedData {
if (loading !== null) { if (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an // If a loading.tsx boundary is present, wrap the component data in an
...@@ -1239,6 +1248,6 @@ function createSeedData( ...@@ -1239,6 +1248,6 @@ function createSeedData(
null, null,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch, hasRuntimePrefetch,
varyParams, varyParamsAccumulator ? getVaryParamsThenable(varyParamsAccumulator) : null,
] ]
} }
This diff is collapsed.
...@@ -4,6 +4,7 @@ import type { ResponseCookies } from '../web/spec-extension/cookies' ...@@ -4,6 +4,7 @@ import type { ResponseCookies } from '../web/spec-extension/cookies'
import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers' import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies' import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
import type { CacheSignal } from './cache-signal' import type { CacheSignal } from './cache-signal'
import type { ResponseVaryParamsAccumulator } from './vary-params'
import type { DynamicTrackingState } from './dynamic-rendering' import type { DynamicTrackingState } from './dynamic-rendering'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
...@@ -207,6 +208,13 @@ interface PrerenderStoreModernCommon ...@@ -207,6 +208,13 @@ interface PrerenderStoreModernCommon
* subsequent dynamic render. * subsequent dynamic render.
*/ */
readonly hmrRefreshHash: string | undefined 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 { interface StaticPrerenderStoreCommon {
......
...@@ -3,6 +3,11 @@ import { ...@@ -3,6 +3,11 @@ import {
type WorkStore, type WorkStore,
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import type { OpaqueFallbackRouteParams } from './fallback-params' 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 { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
...@@ -48,10 +53,15 @@ export function createParamsFromClient( ...@@ -48,10 +53,15 @@ export function createParamsFromClient(
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': 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( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
workStore, workStore,
workUnitStore workUnitStore,
varyParamsAccumulator
) )
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -87,12 +97,23 @@ export function createParamsFromClient( ...@@ -87,12 +97,23 @@ export function createParamsFromClient(
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
export type CreateServerParamsForMetadata = typeof createServerParamsForMetadata 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 // routes always runs in RSC context so it is equivalent to a Server Page Component
export function createServerParamsForRoute( export function createServerParamsForRoute(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<Params> { ): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
...@@ -104,7 +125,8 @@ export function createServerParamsForRoute( ...@@ -104,7 +125,8 @@ export function createServerParamsForRoute(
return createStaticPrerenderParams( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
workStore, workStore,
workUnitStore workUnitStore,
varyParamsAccumulator
) )
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -113,7 +135,11 @@ export function createServerParamsForRoute( ...@@ -113,7 +135,11 @@ export function createServerParamsForRoute(
'createServerParamsForRoute should not be called in cache contexts.' 'createServerParamsForRoute should not be called in cache contexts.'
) )
case 'prerender-runtime': case 'prerender-runtime':
return createRuntimePrerenderParams(underlyingParams, workUnitStore) return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
)
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev` // Semantically we only need the dev tracking when running in `next dev`
...@@ -138,7 +164,8 @@ export function createServerParamsForRoute( ...@@ -138,7 +164,8 @@ export function createServerParamsForRoute(
export function createServerParamsForServerSegment( export function createServerParamsForServerSegment(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<Params> { ): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
...@@ -150,7 +177,8 @@ export function createServerParamsForServerSegment( ...@@ -150,7 +177,8 @@ export function createServerParamsForServerSegment(
return createStaticPrerenderParams( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
workStore, workStore,
workUnitStore workUnitStore,
varyParamsAccumulator
) )
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -159,7 +187,11 @@ export function createServerParamsForServerSegment( ...@@ -159,7 +187,11 @@ export function createServerParamsForServerSegment(
'createServerParamsForServerSegment should not be called in cache contexts.' 'createServerParamsForServerSegment should not be called in cache contexts.'
) )
case 'prerender-runtime': case 'prerender-runtime':
return createRuntimePrerenderParams(underlyingParams, workUnitStore) return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
)
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev` // Semantically we only need the dev tracking when running in `next dev`
...@@ -238,8 +270,14 @@ export function createPrerenderParamsForClientSegment( ...@@ -238,8 +270,14 @@ export function createPrerenderParamsForClientSegment(
function createStaticPrerenderParams( function createStaticPrerenderParams(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: StaticPrerenderStore prerenderStore: StaticPrerenderStore,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> { ): Promise<Params> {
const underlyingParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams
switch (prerenderStore.type) { switch (prerenderStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': { case 'prerender-client': {
...@@ -252,7 +290,7 @@ function createStaticPrerenderParams( ...@@ -252,7 +290,7 @@ function createStaticPrerenderParams(
// we are in cacheComponents mode we encode this as a promise that never // we are in cacheComponents mode we encode this as a promise that never
// resolves. // resolves.
return makeHangingParams( return makeHangingParams(
underlyingParams, underlyingParamsWithVarying,
workStore, workStore,
prerenderStore prerenderStore
) )
...@@ -267,7 +305,7 @@ function createStaticPrerenderParams( ...@@ -267,7 +305,7 @@ function createStaticPrerenderParams(
for (const key in underlyingParams) { for (const key in underlyingParams) {
if (fallbackParams.has(key)) { if (fallbackParams.has(key)) {
return makeErroringParams( return makeErroringParams(
underlyingParams, underlyingParamsWithVarying,
fallbackParams, fallbackParams,
workStore, workStore,
prerenderStore prerenderStore
...@@ -283,16 +321,22 @@ function createStaticPrerenderParams( ...@@ -283,16 +321,22 @@ function createStaticPrerenderParams(
prerenderStore satisfies never prerenderStore satisfies never
} }
return makeUntrackedParams(underlyingParams) return makeUntrackedParams(underlyingParamsWithVarying)
} }
function createRuntimePrerenderParams( function createRuntimePrerenderParams(
underlyingParams: Params, underlyingParams: Params,
workUnitStore: PrerenderStoreModernRuntime workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> { ): Promise<Params> {
const underlyingParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams
return delayUntilRuntimeStage( return delayUntilRuntimeStage(
workUnitStore, workUnitStore,
makeUntrackedParams(underlyingParams) makeUntrackedParams(underlyingParamsWithVarying)
) )
} }
......
...@@ -17,6 +17,7 @@ import { makeHangingPromise } from '../dynamic-rendering-utils' ...@@ -17,6 +17,7 @@ import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { ParamValue } from './params' import type { ParamValue } from './params'
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils' import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
import { actionAsyncStorage } from '../app-render/action-async-storage.external' 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. * Used for the compiler-generated `next/root-params` module.
...@@ -83,6 +84,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -83,6 +84,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
workUnitStore satisfies never workUnitStore satisfies never
} }
} }
accumulateRootVaryParam(paramName)
return Promise.resolve(workUnitStore.rootParams[paramName]) return Promise.resolve(workUnitStore.rootParams[paramName])
} }
...@@ -148,6 +151,7 @@ function createPrerenderRootParamPromise( ...@@ -148,6 +151,7 @@ function createPrerenderRootParamPromise(
} }
// If the param is not a fallback param, we just return the statically available value. // If the param is not a fallback param, we just return the statically available value.
accumulateRootVaryParam(paramName)
return Promise.resolve(underlyingParams[paramName]) return Promise.resolve(underlyingParams[paramName])
} }
......
import type { WorkStore } from '../app-render/work-async-storage.external' 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 { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
...@@ -73,12 +78,22 @@ export function createSearchParamsFromClient( ...@@ -73,12 +78,22 @@ export function createSearchParamsFromClient(
} }
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
export const createServerSearchParamsForMetadata = export function createServerSearchParamsForMetadata(
createServerSearchParamsForServerPage underlyingSearchParams: SearchParams,
workStore: WorkStore
): Promise<SearchParams> {
const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()
return createServerSearchParamsForServerPage(
underlyingSearchParams,
workStore,
metadataVaryParamsAccumulator
)
}
export function createServerSearchParamsForServerPage( export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
): Promise<SearchParams> { ): Promise<SearchParams> {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
...@@ -97,7 +112,8 @@ export function createServerSearchParamsForServerPage( ...@@ -97,7 +112,8 @@ export function createServerSearchParamsForServerPage(
case 'prerender-runtime': case 'prerender-runtime':
return createRuntimePrerenderSearchParams( return createRuntimePrerenderSearchParams(
underlyingSearchParams, underlyingSearchParams,
workUnitStore workUnitStore,
varyParamsAccumulator
) )
case 'request': case 'request':
return createRenderSearchParams( return createRenderSearchParams(
...@@ -181,11 +197,16 @@ function createStaticPrerenderSearchParams( ...@@ -181,11 +197,16 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams( function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workUnitStore: PrerenderStoreModernRuntime workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<SearchParams> { ): Promise<SearchParams> {
const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
: underlyingSearchParams
return delayUntilRuntimeStage( return delayUntilRuntimeStage(
workUnitStore, workUnitStore,
makeUntrackedSearchParams(underlyingSearchParams) makeUntrackedSearchParams(underlyingSearchParamsWithVarying)
) )
} }
......
...@@ -420,6 +420,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -420,6 +420,7 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null,
}) })
let prospectiveResult let prospectiveResult
...@@ -516,6 +517,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -516,6 +517,7 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null,
}) })
let responseHandled = false let responseHandled = false
......
...@@ -11,6 +11,8 @@ export type LoadingModuleData = ...@@ -11,6 +11,8 @@ export type LoadingModuleData =
| [React.JSX.Element, React.ReactNode, React.ReactNode] | [React.JSX.Element, React.ReactNode, React.ReactNode]
| null | null
import type { VaryParamsThenable } from './segment-cache/vary-params-decoding'
/** viewport metadata node */ /** viewport metadata node */
export type HeadData = React.ReactNode export type HeadData = React.ReactNode
...@@ -194,16 +196,20 @@ export type CacheNodeSeedData = [ ...@@ -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` */ /** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
hasRuntimePrefetch: boolean, hasRuntimePrefetch: boolean,
/** /**
* The set of params that this segment's server-rendered output depends on. * A thenable that resolves to the set of route params this segment accessed
* Used by the client cache to determine which entries can be reused across * during server rendering. Used by the client router to determine cache key
* different param values. * 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 * - null thenable: tracking was not enabled for this render (e.g., not a
* params vary) * prerender). Treat conservatively - assume all params vary.
* - Empty set means no params were accessed (segment is reusable for any * - Thenable resolves to empty Set: segment accesses no params (e.g., client
* param values) * 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 = [ export type FlightDataSegment = [
...@@ -248,6 +254,10 @@ export type InitialRSCPayload = { ...@@ -248,6 +254,10 @@ export type InitialRSCPayload = {
G: [React.ComponentType<any>, React.ReactNode | undefined] G: [React.ComponentType<any>, React.ReactNode | undefined]
/** prerendered */ /** prerendered */
S: boolean S: boolean
/**
* headVaryParams - vary params for the head (metadata) of the response.
*/
h: VaryParamsThenable | null
} }
// Response from `createFromFetch` for normal rendering // Response from `createFromFetch` for normal rendering
...@@ -264,6 +274,8 @@ export type NavigationFlightResponse = { ...@@ -264,6 +274,8 @@ export type NavigationFlightResponse = {
i: boolean i: boolean
/** runtimePrefetch - [isPartial, staleTime]. Only present in runtime prefetch responses. */ /** runtimePrefetch - [isPartial, staleTime]. Only present in runtime prefetch responses. */
rp?: [boolean, number] rp?: [boolean, number]
/** headVaryParams */
h: VaryParamsThenable | null
} }
// Response from `createFromFetch` for server actions. Action's flight data can be 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() { 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 @@ ...@@ -3,6 +3,9 @@
*/ */
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: {
optimisticRouting: true,
},
} }
module.exports = nextConfig module.exports = nextConfig
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