Unverified Commit 5dd48e35 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Add `unstable_dynamicStaleTime` route segment config (#91437)

## Background

Next.js has an existing global config,
`experimental.staleTimes.dynamic`, that controls how long the
client-side router cache retains data from dynamic navigation responses.
By default this is 0 — meaning dynamic data is always refetched on every
navigation. Some users set this to a higher value (e.g. 30 seconds) so
that navigating back to a recently visited page reuses the cached
response instead of making a new request.

The limitation of the global config is that it applies uniformly to
every page in the app. Users have asked for the ability to set different
stale times for different pages — for example, a dashboard page that
should always show fresh data vs. a product listing page where it's
acceptable to show slightly stale data for a smoother navigation
experience.

## What this PR adds

`export const unstable_dynamicStaleTime` is a per-page version of
`staleTimes.dynamic`. It accepts a number in seconds with the same unit
and semantics, but scoped to a single page. When present, it overrides
the global config for that page — whether the per-page value is larger
or smaller than the global default. Static and cached responses are
unaffected.

When parallel routes render multiple pages in a single response, the
minimum value across all parallel slots wins, consistent with how stale
times compose generally.

Exporting this from a layout is a build error (pages only).

## Relationship to Cache Components

The recommended way to control data freshness in Next.js is to use Cache
Components (`"use cache"`) with `cacheLife`. This API exists as a
simpler migration path for apps that are already using
`staleTimes.dynamic` and haven't yet adopted Cache Components. It's
prefixed with `unstable_` not because the implementation is unstable,
but because it's not the recommended long-term idiom — apps should
migrate to Cache Components for more granular and composable control
over data freshness.

Based on the design from #88609.
Co-authored-by: 's avatarJimmy Lai <laijimmy0@gmail.com>
Co-authored-by: 's avatarSam Selikoff <sam.selikoff@gmail.com>
parent 9bec0cce
...@@ -1133,5 +1133,7 @@ ...@@ -1133,5 +1133,7 @@
"1132": "Route %s used \\`draftMode()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context", "1132": "Route %s used \\`draftMode()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1133": "createSearchParamsFromClient should not be called inside generateStaticParams.", "1133": "createSearchParamsFromClient should not be called inside generateStaticParams.",
"1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context", "1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1135": "\"use cache\" cannot be used outside of App Router. Expected a WorkUnitStore." "1135": "\"use cache\" cannot be used outside of App Router. Expected a WorkUnitStore.",
"1136": "Page \"%s\" cannot use both \\`export const unstable_dynamicStaleTime\\` and \\`export const unstable_instant\\`.",
"1137": "\"%s\" cannot use \\`export const unstable_dynamicStaleTime\\`. This config is only supported in page files, not layouts."
} }
...@@ -691,6 +691,23 @@ export async function getAppPageStaticInfo({ ...@@ -691,6 +691,23 @@ export async function getAppPageStaticInfo({
) )
} }
// Prevent unstable_dynamicStaleTime in layouts.
if ('unstable_dynamicStaleTime' in config) {
const isLayout = /\/layout\.[^/]+$/.test(pageFilePath)
if (isLayout) {
throw new Error(
`"${page}" cannot use \`export const unstable_dynamicStaleTime\`. This config is only supported in page files, not layouts.`
)
}
}
// Prevent combining unstable_dynamicStaleTime and unstable_instant.
if ('unstable_dynamicStaleTime' in config && 'unstable_instant' in config) {
throw new Error(
`Page "${page}" cannot use both \`export const unstable_dynamicStaleTime\` and \`export const unstable_instant\`.`
)
}
return { return {
type: PAGE_TYPES.APP, type: PAGE_TYPES.APP,
rsc, rsc,
......
...@@ -145,6 +145,13 @@ const AppSegmentConfigSchema = z.object({ ...@@ -145,6 +145,13 @@ const AppSegmentConfigSchema = z.object({
*/ */
unstable_instant: InstantConfigSchema.optional(), unstable_instant: InstantConfigSchema.optional(),
/**
* The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data.
* Pages only — not allowed in layouts.
*/
unstable_dynamicStaleTime: z.number().int().nonnegative().optional(),
/** /**
* The preferred region for the page. * The preferred region for the page.
*/ */
...@@ -188,6 +195,11 @@ export function parseAppSegmentConfig( ...@@ -188,6 +195,11 @@ export function parseAppSegmentConfig(
message: `Invalid unstable_instant value ${JSON.stringify(ctx.data)} on "${route}", must be an object with \`prefetch: "static"\` or \`prefetch: "runtime"\`, or \`false\`. Read more at https://nextjs.org/docs/messages/invalid-instant-configuration`, message: `Invalid unstable_instant value ${JSON.stringify(ctx.data)} on "${route}", must be an object with \`prefetch: "static"\` or \`prefetch: "runtime"\`, or \`false\`. Read more at https://nextjs.org/docs/messages/invalid-instant-configuration`,
} }
} }
case 'unstable_dynamicStaleTime': {
return {
message: `Invalid unstable_dynamicStaleTime value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number`,
}
}
default: default:
} }
} }
...@@ -242,6 +254,13 @@ export type AppSegmentConfig = { ...@@ -242,6 +254,13 @@ export type AppSegmentConfig = {
*/ */
unstable_instant?: Instant unstable_instant?: Instant
/**
* The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data.
* Pages only — not allowed in layouts.
*/
unstable_dynamicStaleTime?: number
/** /**
* The preferred region for the page. * The preferred region for the page.
*/ */
......
...@@ -72,6 +72,7 @@ checkFields<Diff<{ ...@@ -72,6 +72,7 @@ checkFields<Diff<{
config?: {} config?: {}
generateStaticParams?: Function generateStaticParams?: Function
unstable_instant?: InstantConfigForTypeCheckInternal unstable_instant?: InstantConfigForTypeCheckInternal
unstable_dynamicStaleTime?: number
revalidate?: RevalidateRange<TEntry> | false revalidate?: RevalidateRange<TEntry> | false
dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static' dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
dynamicParams?: boolean dynamicParams?: boolean
......
...@@ -14,6 +14,10 @@ import { ...@@ -14,6 +14,10 @@ import {
writeStaticStageResponseIntoCache, writeStaticStageResponseIntoCache,
} from '../segment-cache/cache' } from '../segment-cache/cache'
import { FetchStrategy } from '../segment-cache/types' import { FetchStrategy } from '../segment-cache/types'
import {
UnknownDynamicStaleTime,
computeDynamicStaleAt,
} from '../segment-cache/bfcache'
import { decodeStaticStage } from './fetch-server-response' import { decodeStaticStage } from './fetch-server-response'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes' import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
...@@ -41,6 +45,7 @@ export function createInitialRouterState({ ...@@ -41,6 +45,7 @@ export function createInitialRouterState({
l: initialStaticStageByteLength, l: initialStaticStageByteLength,
h: initialHeadVaryParams, h: initialHeadVaryParams,
p: initialRuntimePrefetchStream, p: initialRuntimePrefetchStream,
d: initialDynamicStaleTimeSeconds,
} = initialRSCPayload } = initialRSCPayload
// When initialized on the server, the canonical URL is provided as an array of parts. // When initialized on the server, the canonical URL is provided as an array of parts.
...@@ -87,7 +92,11 @@ export function createInitialRouterState({ ...@@ -87,7 +92,11 @@ export function createInitialRouterState({
navigatedAt, navigatedAt,
initialRouteTree, initialRouteTree,
initialSeedData, initialSeedData,
initialHead initialHead,
computeDynamicStaleAt(
navigatedAt,
initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime
)
) )
// The following only applies in the browser (location !== null) since neither // The following only applies in the browser (location !== null) since neither
......
...@@ -25,7 +25,6 @@ import { ...@@ -25,7 +25,6 @@ import {
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
NEXT_HMR_REFRESH_HEADER, NEXT_HMR_REFRESH_HEADER,
NEXT_DID_POSTPONE_HEADER, NEXT_DID_POSTPONE_HEADER,
NEXT_ROUTER_STALE_TIME_HEADER,
NEXT_HTML_REQUEST_ID_HEADER, NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
} from '../app-router-headers' } from '../app-router-headers'
...@@ -43,6 +42,7 @@ import { getDeploymentId } from '../../../shared/lib/deployment-id' ...@@ -43,6 +42,7 @@ import { getDeploymentId } from '../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../navigation-build-id' import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { stripIsPartialByte } from '../segment-cache/cache' import { stripIsPartialByte } from '../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../segment-cache/bfcache'
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
...@@ -81,7 +81,7 @@ type SpaFetchServerResponseResult = { ...@@ -81,7 +81,7 @@ type SpaFetchServerResponseResult = {
couldBeIntercepted: boolean couldBeIntercepted: boolean
supportsPerSegmentPrefetching: boolean supportsPerSegmentPrefetching: boolean
postponed: boolean postponed: boolean
staleTime: number dynamicStaleTime: number
staticStageData: StaticStageData | null staticStageData: StaticStageData | null
runtimePrefetchStream: ReadableStream<Uint8Array> | null runtimePrefetchStream: ReadableStream<Uint8Array> | null
responseHeaders: Headers responseHeaders: Headers
...@@ -196,13 +196,6 @@ export async function fetchServerResponse( ...@@ -196,13 +196,6 @@ export async function fetchServerResponse(
const contentType = res.headers.get('content-type') || '' const contentType = res.headers.get('content-type') || ''
const interception = !!res.headers.get('vary')?.includes(NEXT_URL) const interception = !!res.headers.get('vary')?.includes(NEXT_URL)
const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER) const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)
const staleTimeHeaderSeconds = res.headers.get(
NEXT_ROUTER_STALE_TIME_HEADER
)
const staleTime =
staleTimeHeaderSeconds !== null
? parseInt(staleTimeHeaderSeconds, 10) * 1000
: -1
let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER) let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
...@@ -289,7 +282,11 @@ export async function fetchServerResponse( ...@@ -289,7 +282,11 @@ export async function fetchServerResponse(
couldBeIntercepted: interception, couldBeIntercepted: interception,
supportsPerSegmentPrefetching: flightResponse.S, supportsPerSegmentPrefetching: flightResponse.S,
postponed, postponed,
staleTime, // The dynamicStaleTime is only present in the response body when
// a page exports unstable_dynamicStaleTime and this is a dynamic render.
// When absent (UnknownDynamicStaleTime), the client falls back to the
// global DYNAMIC_STALETIME_MS. The value is in seconds.
dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,
staticStageData, staticStageData,
runtimePrefetchStream: flightResponse.p ?? null, runtimePrefetchStream: flightResponse.p ?? null,
responseHeaders: res.headers, responseHeaders: res.headers,
......
...@@ -53,8 +53,9 @@ import { ...@@ -53,8 +53,9 @@ import {
readFromBFCacheDuringRegularNavigation, readFromBFCacheDuringRegularNavigation,
writeToBFCache, writeToBFCache,
writeHeadToBFCache, writeHeadToBFCache,
updateBFCacheEntryStaleAt,
computeDynamicStaleAt,
} from '../segment-cache/bfcache' } from '../segment-cache/bfcache'
import { DYNAMIC_STALETIME_MS } from './reducers/navigate-reducer'
// This is yet another tree type that is used to track pending promises that // This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of // need to be fulfilled once the dynamic data is received. The terminal nodes of
...@@ -132,7 +133,8 @@ export function createInitialCacheNodeForHydration( ...@@ -132,7 +133,8 @@ export function createInitialCacheNodeForHydration(
navigatedAt: number, navigatedAt: number,
initialTree: RouteTree, initialTree: RouteTree,
seedData: CacheNodeSeedData | null, seedData: CacheNodeSeedData | null,
seedHead: HeadData seedHead: HeadData,
seedDynamicStaleAt: number
): NavigationTask { ): NavigationTask {
// Create the initial cache node tree, using the data embedded into the // Create the initial cache node tree, using the data embedded into the
// HTML document. // HTML document.
...@@ -147,6 +149,7 @@ export function createInitialCacheNodeForHydration( ...@@ -147,6 +149,7 @@ export function createInitialCacheNodeForHydration(
FreshnessPolicy.Hydration, FreshnessPolicy.Hydration,
seedData, seedData,
seedHead, seedHead,
seedDynamicStaleAt,
false, false,
accumulation accumulation
) )
...@@ -193,6 +196,7 @@ export function startPPRNavigation( ...@@ -193,6 +196,7 @@ export function startPPRNavigation(
freshness: FreshnessPolicy, freshness: FreshnessPolicy,
seedData: CacheNodeSeedData | null, seedData: CacheNodeSeedData | null,
seedHead: HeadData | null, seedHead: HeadData | null,
seedDynamicStaleAt: number,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
accumulation: NavigationRequestAccumulation accumulation: NavigationRequestAccumulation
): NavigationTask | null { ): NavigationTask | null {
...@@ -214,6 +218,7 @@ export function startPPRNavigation( ...@@ -214,6 +218,7 @@ export function startPPRNavigation(
didFindRootLayout, didFindRootLayout,
seedData, seedData,
seedHead, seedHead,
seedDynamicStaleAt,
isSamePageNavigation, isSamePageNavigation,
parentNeedsDynamicRequest, parentNeedsDynamicRequest,
oldRootRefreshState, oldRootRefreshState,
...@@ -233,6 +238,7 @@ function updateCacheNodeOnNavigation( ...@@ -233,6 +238,7 @@ function updateCacheNodeOnNavigation(
didFindRootLayout: boolean, didFindRootLayout: boolean,
seedData: CacheNodeSeedData | null, seedData: CacheNodeSeedData | null,
seedHead: HeadData | null, seedHead: HeadData | null,
seedDynamicStaleAt: number,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
parentNeedsDynamicRequest: boolean, parentNeedsDynamicRequest: boolean,
oldRootRefreshState: RefreshState, oldRootRefreshState: RefreshState,
...@@ -290,6 +296,7 @@ function updateCacheNodeOnNavigation( ...@@ -290,6 +296,7 @@ function updateCacheNodeOnNavigation(
freshness, freshness,
seedData, seedData,
seedHead, seedHead,
seedDynamicStaleAt,
parentNeedsDynamicRequest, parentNeedsDynamicRequest,
accumulation accumulation
) )
...@@ -356,7 +363,8 @@ function updateCacheNodeOnNavigation( ...@@ -356,7 +363,8 @@ function updateCacheNodeOnNavigation(
seedRsc, seedRsc,
newMetadataVaryPath, newMetadataVaryPath,
seedHead, seedHead,
freshness freshness,
seedDynamicStaleAt
) )
newCacheNode = result.cacheNode newCacheNode = result.cacheNode
needsDynamicRequest = result.needsDynamicRequest needsDynamicRequest = result.needsDynamicRequest
...@@ -486,6 +494,7 @@ function updateCacheNodeOnNavigation( ...@@ -486,6 +494,7 @@ function updateCacheNodeOnNavigation(
childDidFindRootLayout, childDidFindRootLayout,
seedDataChild ?? null, seedDataChild ?? null,
seedHeadChild, seedHeadChild,
seedDynamicStaleAt,
isSamePageNavigation, isSamePageNavigation,
parentNeedsDynamicRequest || needsDynamicRequest, parentNeedsDynamicRequest || needsDynamicRequest,
oldRootRefreshState, oldRootRefreshState,
...@@ -600,6 +609,7 @@ function createCacheNodeOnNavigation( ...@@ -600,6 +609,7 @@ function createCacheNodeOnNavigation(
freshness: FreshnessPolicy, freshness: FreshnessPolicy,
seedData: CacheNodeSeedData | null, seedData: CacheNodeSeedData | null,
seedHead: HeadData | null, seedHead: HeadData | null,
seedDynamicStaleAt: number,
parentNeedsDynamicRequest: boolean, parentNeedsDynamicRequest: boolean,
accumulation: NavigationRequestAccumulation accumulation: NavigationRequestAccumulation
): NavigationTask { ): NavigationTask {
...@@ -625,7 +635,8 @@ function createCacheNodeOnNavigation( ...@@ -625,7 +635,8 @@ function createCacheNodeOnNavigation(
seedRsc, seedRsc,
newMetadataVaryPath, newMetadataVaryPath,
seedHead, seedHead,
freshness freshness,
seedDynamicStaleAt
) )
const newCacheNode = result.cacheNode const newCacheNode = result.cacheNode
const needsDynamicRequest = result.needsDynamicRequest const needsDynamicRequest = result.needsDynamicRequest
...@@ -661,6 +672,7 @@ function createCacheNodeOnNavigation( ...@@ -661,6 +672,7 @@ function createCacheNodeOnNavigation(
freshness, freshness,
seedDataChild ?? null, seedDataChild ?? null,
seedHead, seedHead,
seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest, parentNeedsDynamicRequest || needsDynamicRequest,
accumulation accumulation
) )
...@@ -882,7 +894,8 @@ function createCacheNodeForSegment( ...@@ -882,7 +894,8 @@ function createCacheNodeForSegment(
seedRsc: React.ReactNode | null, seedRsc: React.ReactNode | null,
metadataVaryPath: PageVaryPath | null, metadataVaryPath: PageVaryPath | null,
seedHead: HeadData | null, seedHead: HeadData | null,
freshness: FreshnessPolicy freshness: FreshnessPolicy,
dynamicStaleAt: number
): { cacheNode: CacheNode; needsDynamicRequest: boolean } { ): { cacheNode: CacheNode; needsDynamicRequest: boolean } {
// Construct a new CacheNode using data from the BFCache, the client's // Construct a new CacheNode using data from the BFCache, the client's
// Segment Cache, or seeded from a server response. // Segment Cache, or seeded from a server response.
...@@ -905,29 +918,23 @@ function createCacheNodeForSegment( ...@@ -905,29 +918,23 @@ function createCacheNodeForSegment(
// the BFCache. // the BFCache.
switch (freshness) { switch (freshness) {
case FreshnessPolicy.Default: { case FreshnessPolicy.Default: {
// When experimental.staleTimes.dynamic config is set, we read from the // Check BFCache during regular navigations. The entry's staleAt
// BFCache even during regular navigations. (This is not a recommended API // determines whether it's still fresh. This is used when
// with Cache Components, but it's supported for backwards compatibility. // staleTimes.dynamic is configured globally or when a page exports
// Use cacheLife instead.) // unstable_dynamicStaleTime for per-page control.
const bfcacheEntry = readFromBFCacheDuringRegularNavigation(
// This outer check isn't semantically necessary; even if the configured now,
// stale time is 0, the bfcache will return null, because any entry would tree.varyPath
// have immediately expired. Just an optimization. )
if (DYNAMIC_STALETIME_MS > 0) { if (bfcacheEntry !== null) {
const bfcacheEntry = readFromBFCacheDuringRegularNavigation( return {
now, cacheNode: createCacheNode(
tree.varyPath bfcacheEntry.rsc,
) bfcacheEntry.prefetchRsc,
if (bfcacheEntry !== null) { bfcacheEntry.head,
return { bfcacheEntry.prefetchHead
cacheNode: createCacheNode( ),
bfcacheEntry.rsc, needsDynamicRequest: false,
bfcacheEntry.prefetchRsc,
bfcacheEntry.head,
bfcacheEntry.prefetchHead
),
needsDynamicRequest: false,
}
} }
} }
break break
...@@ -953,9 +960,23 @@ function createCacheNodeForSegment( ...@@ -953,9 +960,23 @@ function createCacheNodeForSegment(
const prefetchRsc = null const prefetchRsc = null
const head = isPage ? seedHead : null const head = isPage ? seedHead : null
const prefetchHead = null const prefetchHead = null
writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead) writeToBFCache(
now,
tree.varyPath,
rsc,
prefetchRsc,
head,
prefetchHead,
dynamicStaleAt
)
if (isPage && metadataVaryPath !== null) { if (isPage && metadataVaryPath !== null) {
writeHeadToBFCache(now, metadataVaryPath, head, prefetchHead) writeHeadToBFCache(
now,
metadataVaryPath,
head,
prefetchHead,
dynamicStaleAt
)
} }
return { return {
cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead), cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),
...@@ -1180,9 +1201,23 @@ function createCacheNodeForSegment( ...@@ -1180,9 +1201,23 @@ function createCacheNodeForSegment(
// Skip BFCache writes for optimistic navigations since they are transient // Skip BFCache writes for optimistic navigations since they are transient
// and will be replaced by the canonical navigation. // and will be replaced by the canonical navigation.
if (freshness !== FreshnessPolicy.Gesture) { if (freshness !== FreshnessPolicy.Gesture) {
writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead) writeToBFCache(
now,
tree.varyPath,
rsc,
prefetchRsc,
head,
prefetchHead,
dynamicStaleAt
)
if (isPage && metadataVaryPath !== null) { if (isPage && metadataVaryPath !== null) {
writeHeadToBFCache(now, metadataVaryPath, head, prefetchHead) writeHeadToBFCache(
now,
metadataVaryPath,
head,
prefetchHead,
dynamicStaleAt
)
} }
} }
...@@ -1583,10 +1618,14 @@ async function fetchMissingDynamicData( ...@@ -1583,10 +1618,14 @@ async function fetchMissingDynamicData(
seed: null, seed: null,
} }
} }
const now = Date.now()
const seed = convertServerPatchToFullTree( const seed = convertServerPatchToFullTree(
now,
task.route, task.route,
result.flightData, result.flightData,
result.renderedSearch result.renderedSearch,
result.dynamicStaleTime
) )
// If the navigation lock is active, wait for it to be released before // If the navigation lock is active, wait for it to be released before
...@@ -1596,8 +1635,6 @@ async function fetchMissingDynamicData( ...@@ -1596,8 +1635,6 @@ async function fetchMissingDynamicData(
await waitForNavigationLock() await waitForNavigationLock()
} }
const now = Date.now()
if (routeCacheEntry !== null && result.staticStageData !== null) { if (routeCacheEntry !== null && result.staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } = const { response: staticStageResponse, isResponsePartial } =
result.staticStageData result.staticStageData
...@@ -1653,11 +1690,16 @@ async function fetchMissingDynamicData( ...@@ -1653,11 +1690,16 @@ async function fetchMissingDynamicData(
}) })
} }
// result.dynamicStaleTime is in seconds (from the server's `d` field).
// Convert to an absolute timestamp using the centralized helper.
const dynamicStaleAt = computeDynamicStaleAt(now, result.dynamicStaleTime)
const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask( const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(
task, task,
seed.routeTree, seed.routeTree,
seed.data, seed.data,
seed.head, seed.head,
dynamicStaleAt,
result.debugInfo result.debugInfo
) )
...@@ -1685,11 +1727,19 @@ function writeDynamicDataIntoNavigationTask( ...@@ -1685,11 +1727,19 @@ function writeDynamicDataIntoNavigationTask(
serverRouteTree: RouteTree, serverRouteTree: RouteTree,
dynamicData: CacheNodeSeedData | null, dynamicData: CacheNodeSeedData | null,
dynamicHead: HeadData, dynamicHead: HeadData,
dynamicStaleAt: number,
debugInfo: Array<any> | null debugInfo: Array<any> | null
): boolean { ): boolean {
if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) { if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) {
task.status = NavigationTaskStatus.Fulfilled task.status = NavigationTaskStatus.Fulfilled
finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo) finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo)
// Update the BFCache entry's staleAt for this segment with the value
// from the dynamic response. This applies the per-page
// unstable_dynamicStaleTime if set, or the default DYNAMIC_STALETIME_MS.
// We only update segments that received dynamic data — static segments
// are unaffected.
updateBFCacheEntryStaleAt(serverRouteTree.varyPath, dynamicStaleAt)
} }
const taskChildren = task.children const taskChildren = task.children
...@@ -1740,6 +1790,7 @@ function writeDynamicDataIntoNavigationTask( ...@@ -1740,6 +1790,7 @@ function writeDynamicDataIntoNavigationTask(
serverRouteTreeChild, serverRouteTreeChild,
dynamicDataChild, dynamicDataChild,
dynamicHead, dynamicHead,
dynamicStaleAt,
debugInfo debugInfo
) )
if (childDidReceiveUnknownParallelRoute) { if (childDidReceiveUnknownParallelRoute) {
......
...@@ -11,7 +11,10 @@ import { ...@@ -11,7 +11,10 @@ import {
import { invalidateSegmentCacheEntries } from '../../segment-cache/cache' import { invalidateSegmentCacheEntries } from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
import { invalidateBfCache } from '../../segment-cache/bfcache' import {
invalidateBfCache,
UnknownDynamicStaleTime,
} from '../../segment-cache/bfcache'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -63,13 +66,17 @@ export function refreshDynamicData( ...@@ -63,13 +66,17 @@ export function refreshDynamicData(
// TODO: Eventually we will store this type directly on the state object // TODO: Eventually we will store this type directly on the state object
// instead of reconstructing it on demand. Part of a larger series of // instead of reconstructing it on demand. Part of a larger series of
// refactors to unify the various tree types that the client deals with. // refactors to unify the various tree types that the client deals with.
const now = Date.now()
// TODO: Store the dynamic stale time on the top-level state so it's known
// during restores and refreshes.
const refreshSeed = convertServerPatchToFullTree( const refreshSeed = convertServerPatchToFullTree(
now,
currentFlightRouterState, currentFlightRouterState,
null, null,
currentRenderedSearch currentRenderedSearch,
UnknownDynamicStaleTime
) )
const now = Date.now()
const navigateType = 'replace' const navigateType = 'replace'
return navigateToKnownRoute( return navigateToKnownRoute(
now, now,
......
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
completeTraverseNavigation, completeTraverseNavigation,
convertServerPatchToFullTree, convertServerPatchToFullTree,
} from '../../segment-cache/navigation' } from '../../segment-cache/navigation'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
export function restoreReducer( export function restoreReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -44,14 +45,18 @@ export function restoreReducer( ...@@ -44,14 +45,18 @@ export function restoreReducer(
extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname
const now = Date.now() const now = Date.now()
// TODO: Store the dynamic stale time on the top-level state so it's known
// during restores and refreshes.
const accumulation: NavigationRequestAccumulation = { const accumulation: NavigationRequestAccumulation = {
separateRefreshUrls: null, separateRefreshUrls: null,
scrollRef: null, scrollRef: null,
} }
const restoreSeed = convertServerPatchToFullTree( const restoreSeed = convertServerPatchToFullTree(
now,
treeToRestore, treeToRestore,
null, null,
renderedSearch renderedSearch,
UnknownDynamicStaleTime
) )
const task = startPPRNavigation( const task = startPPRNavigation(
now, now,
...@@ -64,6 +69,7 @@ export function restoreReducer( ...@@ -64,6 +69,7 @@ export function restoreReducer(
FreshnessPolicy.HistoryTraversal, FreshnessPolicy.HistoryTraversal,
null, null,
null, null,
restoreSeed.dynamicStaleAt,
false, false,
accumulation accumulation
) )
......
...@@ -68,7 +68,10 @@ import { ...@@ -68,7 +68,10 @@ import {
import { isExternalURL } from '../../app-router-utils' import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
import { processFetch } from '../fetch-server-response' import { processFetch } from '../fetch-server-response'
import { invalidateBfCache } from '../../segment-cache/bfcache' import {
invalidateBfCache,
UnknownDynamicStaleTime,
} from '../../segment-cache/bfcache'
const createFromFetch = const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch'] createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
...@@ -437,12 +440,16 @@ export function serverActionReducer( ...@@ -437,12 +440,16 @@ export function serverActionReducer(
// subset of the data needed to render the new page, we'll initiate a // subset of the data needed to render the new page, we'll initiate a
// new fetch, like we would for a normal navigation. // new fetch, like we would for a normal navigation.
const redirectCanonicalUrl = createHrefFromUrl(redirectUrl) const redirectCanonicalUrl = createHrefFromUrl(redirectUrl)
const now = Date.now()
// TODO: Store the dynamic stale time on the top-level state so it's
// known during restores and refreshes.
const redirectSeed = convertServerPatchToFullTree( const redirectSeed = convertServerPatchToFullTree(
now,
currentFlightRouterState, currentFlightRouterState,
flightData, flightData,
flightDataRenderedSearch flightDataRenderedSearch,
UnknownDynamicStaleTime
) )
const now = Date.now()
// Learn the route pattern so we can predict it for future navigations. // Learn the route pattern so we can predict it for future navigations.
const metadataVaryPath = redirectSeed.metadataVaryPath const metadataVaryPath = redirectSeed.metadataVaryPath
......
import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
import type { SegmentVaryPath } from './vary-path' import type { SegmentVaryPath } from './vary-path'
/**
* Sentinel value indicating that no per-page dynamic stale time was provided.
* When this is the dynamicStaleTime, the default DYNAMIC_STALETIME_MS is used.
*/
export const UnknownDynamicStaleTime = -1
/**
* Converts a dynamic stale time (in seconds, as sent by the server in the `d`
* field of the Flight response) to an absolute staleAt timestamp. When the
* value is unknown, falls back to the global DYNAMIC_STALETIME_MS.
*/
export function computeDynamicStaleAt(
now: number,
dynamicStaleTimeSeconds: number
): number {
return dynamicStaleTimeSeconds !== UnknownDynamicStaleTime
? now + dynamicStaleTimeSeconds * 1000
: now + DYNAMIC_STALETIME_MS
}
import { import {
setInCacheMap, setInCacheMap,
getFromCacheMap, getFromCacheMap,
...@@ -6,7 +27,6 @@ import { ...@@ -6,7 +27,6 @@ import {
type CacheMap, type CacheMap,
createCacheMap, createCacheMap,
} from './cache-map' } from './cache-map'
import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
export type BFCacheEntry = { export type BFCacheEntry = {
rsc: React.ReactNode | null rsc: React.ReactNode | null
...@@ -16,6 +36,12 @@ export type BFCacheEntry = { ...@@ -16,6 +36,12 @@ export type BFCacheEntry = {
ref: UnknownMapEntry | null ref: UnknownMapEntry | null
size: number size: number
// The time at which this data was received. Used to compute the stale time
// for dynamic prefetches (which use STATIC_STALETIME_MS instead of
// DYNAMIC_STALETIME_MS). Stored explicitly because staleAt may be
// overridden by a per-page unstable_dynamicStaleTime, which would break
// any reverse calculation from staleAt.
navigatedAt: number
staleAt: number staleAt: number
version: number version: number
} }
...@@ -37,7 +63,8 @@ export function writeToBFCache( ...@@ -37,7 +63,8 @@ export function writeToBFCache(
rsc: React.ReactNode, rsc: React.ReactNode,
prefetchRsc: React.ReactNode, prefetchRsc: React.ReactNode,
head: React.ReactNode, head: React.ReactNode,
prefetchHead: React.ReactNode prefetchHead: React.ReactNode,
dynamicStaleAt: number
): void { ): void {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
return return
...@@ -60,9 +87,12 @@ export function writeToBFCache( ...@@ -60,9 +87,12 @@ export function writeToBFCache(
// entirely and use memory pressure events instead. // entirely and use memory pressure events instead.
size: 100, size: 100,
navigatedAt: now,
// A back/forward navigation will disregard the stale time. This field is // A back/forward navigation will disregard the stale time. This field is
// only relevant when staleTimes.dynamic is enabled. // only relevant when staleTimes.dynamic is enabled or unstable_dynamicStaleTime
staleAt: now + DYNAMIC_STALETIME_MS, // is exported by a page.
staleAt: dynamicStaleAt,
version: currentBfCacheVersion, version: currentBfCacheVersion,
} }
const isRevalidation = false const isRevalidation = false
...@@ -73,10 +103,38 @@ export function writeHeadToBFCache( ...@@ -73,10 +103,38 @@ export function writeHeadToBFCache(
now: number, now: number,
varyPath: SegmentVaryPath, varyPath: SegmentVaryPath,
head: React.ReactNode, head: React.ReactNode,
prefetchHead: React.ReactNode prefetchHead: React.ReactNode,
dynamicStaleAt: number
): void { ): void {
// Read the special "segment" that represents the head data. // Read the special "segment" that represents the head data.
writeToBFCache(now, varyPath, head, prefetchHead, null, null) writeToBFCache(now, varyPath, head, prefetchHead, null, null, dynamicStaleAt)
}
/**
* Update the staleAt of an existing BFCache entry. Used after a dynamic
* response arrives with a per-page stale time from `unstable_dynamicStaleTime`.
* The per-page value is authoritative — it overrides whatever staleAt was set
* by the default DYNAMIC_STALETIME_MS.
*/
export function updateBFCacheEntryStaleAt(
varyPath: SegmentVaryPath,
newStaleAt: number
): void {
if (typeof window === 'undefined') {
return
}
const isRevalidation = false
// Read with staleness bypass (-1) so we can update even stale entries
const entry = getFromCacheMap(
-1,
currentBfCacheVersion,
bfcacheMap,
varyPath,
isRevalidation
)
if (entry !== null) {
entry.staleAt = newStaleAt
}
} }
export function readFromBFCache( export function readFromBFCache(
......
...@@ -99,15 +99,12 @@ import { ...@@ -99,15 +99,12 @@ import {
normalizeFlightData, normalizeFlightData,
prepareFlightRouterStateForRequest, prepareFlightRouterStateForRequest,
} from '../../flight-data-helpers' } from '../../flight-data-helpers'
import { import { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
DYNAMIC_STALETIME_MS,
STATIC_STALETIME_MS,
} from '../router-reducer/reducers/navigate-reducer'
import { pingVisibleLinks } from '../links' import { pingVisibleLinks } from '../links'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import { FetchStrategy } from './types' import { FetchStrategy } from './types'
import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'
import { readFromBFCacheDuringRegularNavigation } from './bfcache' import { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'
import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes' import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'
import { convertServerPatchToFullTree, type NavigationSeed } from './navigation' import { convertServerPatchToFullTree, type NavigationSeed } from './navigation'
import { getNavigationBuildId } from '../../navigation-build-id' import { getNavigationBuildId } from '../../navigation-build-id'
...@@ -951,23 +948,20 @@ export function attemptToFulfillDynamicSegmentFromBFCache( ...@@ -951,23 +948,20 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
// regular navigation. // regular navigation.
const varyPath = tree.varyPath const varyPath = tree.varyPath
// The stale time for dynamic prefetches (default: 5 mins) is different from // Read from the BFCache without expiring it (pass -1). We check freshness
// the stale time for regular navigations (default: 0 secs). We adjust the // ourselves using navigatedAt, because the BFCache's staleAt may have been
// current timestamp to account for the difference. // overridden by a per-page unstable_dynamicStaleTime and can't be used to
const adjustedCurrentTime = now - STATIC_STALETIME_MS + DYNAMIC_STALETIME_MS // derive the original request time.
const bfcacheEntry = readFromBFCacheDuringRegularNavigation( const bfcacheEntry = readFromBFCache(varyPath)
adjustedCurrentTime,
varyPath
)
if (bfcacheEntry !== null) { if (bfcacheEntry !== null) {
// Fulfill the prefetch using the bfcache entry. // The stale time for dynamic prefetches (default: 5 mins) is different
// from the stale time for regular navigations (default: 0 secs). Use
// As explained above, the stale time of this prefetch entry is different // navigatedAt to compute the correct expiry for prefetch purposes.
// than the one for the bfcache. Calculate when it was originally requested const dynamicPrefetchStaleAt =
// by subtracting the stale time used by the bfcache. bfcacheEntry.navigatedAt + STATIC_STALETIME_MS
const requestedAt = bfcacheEntry.staleAt - DYNAMIC_STALETIME_MS if (now > dynamicPrefetchStaleAt) {
// Now add the stale time used by dynamic prefetches. return null
const dynamicPrefetchStaleAt = requestedAt + STATIC_STALETIME_MS }
const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full) const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)
const isPartial = false const isPartial = false
...@@ -992,14 +986,13 @@ export function attemptToUpgradeSegmentFromBFCache( ...@@ -992,14 +986,13 @@ export function attemptToUpgradeSegmentFromBFCache(
tree: RouteTree tree: RouteTree
): FulfilledSegmentCacheEntry | null { ): FulfilledSegmentCacheEntry | null {
const varyPath = tree.varyPath const varyPath = tree.varyPath
const adjustedCurrentTime = now - STATIC_STALETIME_MS + DYNAMIC_STALETIME_MS const bfcacheEntry = readFromBFCache(varyPath)
const bfcacheEntry = readFromBFCacheDuringRegularNavigation(
adjustedCurrentTime,
varyPath
)
if (bfcacheEntry !== null) { if (bfcacheEntry !== null) {
const requestedAt = bfcacheEntry.staleAt - DYNAMIC_STALETIME_MS const dynamicPrefetchStaleAt =
const dynamicPrefetchStaleAt = requestedAt + STATIC_STALETIME_MS bfcacheEntry.navigatedAt + STATIC_STALETIME_MS
if (now > dynamicPrefetchStaleAt) {
return null
}
const pendingSegment = upgradeToPendingSegment( const pendingSegment = upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now), createDetachedSegmentCacheEntry(now),
FetchStrategy.Full FetchStrategy.Full
...@@ -2292,9 +2285,12 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2292,9 +2285,12 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
return null return null
} }
const navigationSeed = convertServerPatchToFullTree( const navigationSeed = convertServerPatchToFullTree(
now,
dynamicRequestTree, dynamicRequestTree,
flightDatas, flightDatas,
renderedSearch renderedSearch,
// Not needed for prefetch responses; pass unknown to use the default.
UnknownDynamicStaleTime
) )
fulfilledEntries = writeDynamicRenderResponseIntoCache( fulfilledEntries = writeDynamicRenderResponseIntoCache(
now, now,
...@@ -2395,9 +2391,11 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2395,9 +2391,11 @@ function writeDynamicTreeResponseIntoCache(
// enabled everywhere. Tree prefetches should never include segment data. We // enabled everywhere. Tree prefetches should never include segment data. We
// can delete it. Leaving for a subsequent PR. // can delete it. Leaving for a subsequent PR.
const navigationSeed = convertServerPatchToFullTree( const navigationSeed = convertServerPatchToFullTree(
now,
flightRouterState, flightRouterState,
normalizedFlightDataResult, normalizedFlightDataResult,
renderedSearch renderedSearch,
UnknownDynamicStaleTime
) )
const buildId = const buildId =
response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
...@@ -2921,9 +2919,11 @@ export function writeStaticStageResponseIntoCache( ...@@ -2921,9 +2919,11 @@ export function writeStaticStageResponseIntoCache(
return return
} }
const navigationSeed = convertServerPatchToFullTree( const navigationSeed = convertServerPatchToFullTree(
now,
baseTree, baseTree,
flightDatas, flightDatas,
renderedSearch renderedSearch,
UnknownDynamicStaleTime
) )
writeDynamicRenderResponseIntoCache( writeDynamicRenderResponseIntoCache(
now, now,
...@@ -2979,9 +2979,11 @@ export async function processRuntimePrefetchStream( ...@@ -2979,9 +2979,11 @@ export async function processRuntimePrefetchStream(
return null return null
} }
const navigationSeed = convertServerPatchToFullTree( const navigationSeed = convertServerPatchToFullTree(
now,
baseTree, baseTree,
flightDatas, flightDatas,
renderedSearch renderedSearch,
UnknownDynamicStaleTime
) )
return { return {
......
...@@ -38,6 +38,7 @@ import type { AppRouterState } from '../router-reducer/router-reducer-types' ...@@ -38,6 +38,7 @@ import type { AppRouterState } from '../router-reducer/router-reducer-types'
import { ScrollBehavior } from '../router-reducer/router-reducer-types' import { ScrollBehavior } from '../router-reducer/router-reducer-types'
import { computeChangedPath } from '../router-reducer/compute-changed-path' import { computeChangedPath } from '../router-reducer/compute-changed-path'
import { isJavaScriptURLString } from '../../lib/javascript-url' import { isJavaScriptURLString } from '../../lib/javascript-url'
import { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'
/** /**
* Navigate to a new URL, using the Segment Cache to construct a response. * Navigate to a new URL, using the Segment Cache to construct a response.
...@@ -258,6 +259,7 @@ export function navigateToKnownRoute( ...@@ -258,6 +259,7 @@ export function navigateToKnownRoute(
freshnessPolicy, freshnessPolicy,
navigationSeed.data, navigationSeed.data,
navigationSeed.head, navigationSeed.head,
navigationSeed.dynamicStaleAt,
isSamePageNavigation, isSamePageNavigation,
accumulation accumulation
) )
...@@ -314,6 +316,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -314,6 +316,7 @@ function navigateUsingPrefetchedRouteTree(
metadataVaryPath: route.metadata.varyPath as any, metadataVaryPath: route.metadata.varyPath as any,
data: null, data: null,
head: null, head: null,
dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),
} }
return navigateToKnownRoute( return navigateToKnownRoute(
now, now,
...@@ -406,6 +409,7 @@ async function navigateToUnknownRoute( ...@@ -406,6 +409,7 @@ async function navigateToUnknownRoute(
renderedSearch, renderedSearch,
couldBeIntercepted, couldBeIntercepted,
supportsPerSegmentPrefetching, supportsPerSegmentPrefetching,
dynamicStaleTime,
staticStageData, staticStageData,
runtimePrefetchStream, runtimePrefetchStream,
responseHeaders, responseHeaders,
...@@ -416,9 +420,11 @@ async function navigateToUnknownRoute( ...@@ -416,9 +420,11 @@ async function navigateToUnknownRoute(
// different, we'll need to massage the data a bit. Create FlightRouterState // different, we'll need to massage the data a bit. Create FlightRouterState
// tree that simulates what we'd receive as the result of a prefetch. // tree that simulates what we'd receive as the result of a prefetch.
const navigationSeed = convertServerPatchToFullTree( const navigationSeed = convertServerPatchToFullTree(
now,
currentFlightRouterState, currentFlightRouterState,
flightData, flightData,
renderedSearch renderedSearch,
dynamicStaleTime
) )
// Learn the route pattern so we can predict it for future navigations. // Learn the route pattern so we can predict it for future navigations.
...@@ -736,12 +742,15 @@ export type NavigationSeed = { ...@@ -736,12 +742,15 @@ export type NavigationSeed = {
metadataVaryPath: PageVaryPath | null metadataVaryPath: PageVaryPath | null
data: CacheNodeSeedData | null data: CacheNodeSeedData | null
head: HeadData | null head: HeadData | null
dynamicStaleAt: number
} }
export function convertServerPatchToFullTree( export function convertServerPatchToFullTree(
now: number,
currentTree: FlightRouterState, currentTree: FlightRouterState,
flightData: Array<NormalizedFlightData> | null, flightData: Array<NormalizedFlightData> | null,
renderedSearch: string renderedSearch: string,
dynamicStaleTimeSeconds: number
): NavigationSeed { ): NavigationSeed {
// During a client navigation or prefetch, the server sends back only a patch // During a client navigation or prefetch, the server sends back only a patch
// for the parts of the tree that have changed. // for the parts of the tree that have changed.
...@@ -806,6 +815,7 @@ export function convertServerPatchToFullTree( ...@@ -806,6 +815,7 @@ export function convertServerPatchToFullTree(
data: baseData, data: baseData,
renderedSearch, renderedSearch,
head, head,
dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),
} }
} }
......
...@@ -260,7 +260,10 @@ import { ...@@ -260,7 +260,10 @@ import {
createValidationBoundaryTracking, createValidationBoundaryTracking,
type ValidationBoundaryTracking, type ValidationBoundaryTracking,
} from './instant-validation/boundary-tracking' } from './instant-validation/boundary-tracking'
import type { InstantSample } from '../../build/segment-config/app/app-segment-config' import type {
AppSegmentConfig,
InstantSample,
} from '../../build/segment-config/app/app-segment-config'
import { ResponseCookies } from '../web/spec-extension/cookies' import { ResponseCookies } from '../web/spec-extension/cookies'
import { isInstantValidationError } from './instant-validation/instant-validation-error' import { isInstantValidationError } from './instant-validation/instant-validation-error'
...@@ -431,6 +434,48 @@ function parseRequestHeaders( ...@@ -431,6 +434,48 @@ function parseRequestHeaders(
} }
} }
/**
* Walks the loader tree to find the minimum `unstable_dynamicStaleTime` exported by
* any page module. Returns null if no page exports the config.
*
* This only reads static exports from page modules — it does not render any
* server components, so it's cheap to call.
*
* TODO: Move this to the prefetch hints file so we don't have to walk the
* tree on every render.
*/
async function getDynamicStaleTime(tree: LoaderTree): Promise<number | null> {
const { page, parallelRoutes } = parseLoaderTree(tree)
let result: number | null = null
// Only pages (not layouts) can export unstable_dynamicStaleTime.
if (typeof page !== 'undefined') {
const pageMod = await page[0]()
if (
pageMod &&
typeof (pageMod as AppSegmentConfig).unstable_dynamicStaleTime ===
'number'
) {
const value = (pageMod as AppSegmentConfig).unstable_dynamicStaleTime!
result = result !== null ? Math.min(result, value) : value
}
}
const childPromises: Promise<number | null>[] = []
for (const parallelRouteKey in parallelRoutes) {
childPromises.push(getDynamicStaleTime(parallelRoutes[parallelRouteKey]))
}
const childResults = await Promise.all(childPromises)
for (const childResult of childResults) {
if (childResult !== null) {
result = result !== null ? Math.min(result, childResult) : childResult
}
}
return result
}
function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
const components = loaderTree[2] const components = loaderTree[2]
const hasGlobalNotFound = !!components['global-not-found'] const hasGlobalNotFound = !!components['global-not-found']
...@@ -668,6 +713,20 @@ async function generateDynamicRSCPayload( ...@@ -668,6 +713,20 @@ async function generateDynamicRSCPayload(
baseResponse.p = options.runtimePrefetchStream baseResponse.p = options.runtimePrefetchStream
} }
// Include the per-page dynamic stale time from unstable_dynamicStaleTime, but only
// for dynamic renders (not prerenders/static generation). The client treats
// its presence as authoritative.
// TODO: Move this to the prefetch hints file so we don't have to walk the
// tree on every render.
if (!workStore.isStaticGeneration) {
const dynamicStaleTime = await getDynamicStaleTime(
ctx.componentMod.routeModule.userland.loaderTree
)
if (dynamicStaleTime !== null) {
baseResponse.d = dynamicStaleTime
}
}
return baseResponse return baseResponse
} }
...@@ -1789,6 +1848,14 @@ async function getRSCPayload( ...@@ -1789,6 +1848,14 @@ async function getRSCPayload(
s: staleTimeIterable, s: staleTimeIterable,
l: staticStageByteLengthPromise, l: staticStageByteLengthPromise,
p: runtimePrefetchStream, p: runtimePrefetchStream,
// Include the per-page dynamic stale time from unstable_dynamicStaleTime, but
// only for dynamic renders. The client treats its presence as
// authoritative.
// TODO: Move this to the prefetch hints file so we don't have to walk
// the tree on every render.
d: !workStore.isStaticGeneration
? ((await getDynamicStaleTime(tree)) ?? undefined)
: undefined,
}) })
} }
......
...@@ -357,6 +357,48 @@ async function createComponentTreeInternal( ...@@ -357,6 +357,48 @@ async function createComponentTreeInternal(
} }
} }
// Read unstable_dynamicStaleTime from page modules (not layouts) and track it on
// the store's stale field. This affects the segment cache stale time via
// the StaleTimeIterable.
if (
isPage &&
typeof layoutOrPageMod?.unstable_dynamicStaleTime === 'number'
) {
const pageStaleTime = layoutOrPageMod.unstable_dynamicStaleTime
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.stale > pageStaleTime) {
workUnitStore.stale = pageStaleTime
}
break
case 'request':
if (
workUnitStore.stale === undefined ||
workUnitStore.stale > pageStaleTime
) {
workUnitStore.stale = pageStaleTime
}
break
// createComponentTree is not called for these stores:
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
}
}
const isStaticGeneration = workStore.isStaticGeneration const isStaticGeneration = workStore.isStaticGeneration
// Assume the segment we're rendering contains only partial data if PPR is // Assume the segment we're rendering contains only partial data if PPR is
......
...@@ -156,6 +156,17 @@ const API_DOCS: Record< ...@@ -156,6 +156,17 @@ const API_DOCS: Record<
// `getSemanticDiagnosticsForExportVariableStatement` below, and only provide hover a tooltip + autocomplete. // `getSemanticDiagnosticsForExportVariableStatement` below, and only provide hover a tooltip + autocomplete.
insertText: 'unstable_instant = { prefetch: "static" };', insertText: 'unstable_instant = { prefetch: "static" };',
}, },
unstable_dynamicStaleTime: {
description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \`unstable_instant\`.`,
link: '(docs coming soon)',
type: 'number',
isValid: (value: string) => {
return Number(value.replace(/_/g, '')) >= 0
},
getHint: (value: any) => {
return `Set the dynamic stale time to \`${value}\` seconds.`
},
},
} }
type FullAppSegmentConfig = Required<AppSegmentConfig> type FullAppSegmentConfig = Required<AppSegmentConfig>
......
...@@ -314,6 +314,14 @@ export type InitialRSCPayload = { ...@@ -314,6 +314,14 @@ export type InitialRSCPayload = {
l?: Promise<number> l?: Promise<number>
/** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */ /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */
p?: ReadableStream<Uint8Array> p?: ReadableStream<Uint8Array>
/**
* dynamicStaleTime — Per-page BFCache stale time in seconds, from
* `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls
* how long the client router cache retains dynamic navigation data. This is
* distinct from the `s` field, which controls segment cache (prefetch)
* staleness.
*/
d?: number
} }
// Response from `createFromFetch` for normal rendering // Response from `createFromFetch` for normal rendering
...@@ -336,6 +344,14 @@ export type NavigationFlightResponse = { ...@@ -336,6 +344,14 @@ export type NavigationFlightResponse = {
h: VaryParamsThenable | null h: VaryParamsThenable | null
/** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */ /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */
p?: ReadableStream<Uint8Array> p?: ReadableStream<Uint8Array>
/**
* dynamicStaleTime — Per-page BFCache stale time in seconds, from
* `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls
* how long the client router cache retains dynamic navigation data. This is
* distinct from the `s` field, which controls segment cache (prefetch)
* staleness.
*/
d?: number
} }
// 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
......
import { Suspense } from 'react'
import { connection } from 'next/server'
export const unstable_dynamicStaleTime = 10
async function Content() {
await connection()
return (
<div id="dynamic-stale-10-content">Dynamic content (stale time 10s)</div>
)
}
export default function Page() {
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export const unstable_dynamicStaleTime = 60
async function Content() {
await connection()
return (
<div id="dynamic-stale-60-content">Dynamic content (stale time 60s)</div>
)
}
export default function Page() {
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
export default function Layout({ children }: { children: React.ReactNode }) {
return children
}
import { LinkAccordion } from '../../components/link-accordion'
export default function Page() {
return (
<>
<p>
This page tests per-page dynamic stale time configuration via{' '}
<code>export const unstable_dynamicStaleTime</code>.
</p>
<ul>
<li>
<LinkAccordion href="/per-page-config/dynamic-stale-60">
Dynamic page with stale time of 60 seconds
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/per-page-config/dynamic-stale-10">
Dynamic page with stale time of 10 seconds
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/per-page-config/parallel-slots">
Parallel routes with slots having different stale times (60s and
15s)
</LinkAccordion>
</li>
</ul>
</>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export const unstable_dynamicStaleTime = 60
async function Content() {
await connection()
return <div id="slot-a-content">Slot A content (stale time 60s)</div>
}
export default function Page() {
return (
<Suspense fallback="Loading slot A...">
<Content />
</Suspense>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export const unstable_dynamicStaleTime = 15
async function Content() {
await connection()
return <div id="slot-b-content">Slot B content (stale time 15s)</div>
}
export default function Page() {
return (
<Suspense fallback="Loading slot B...">
<Content />
</Suspense>
)
}
export default function Layout({
children,
slotA,
slotB,
}: {
children: React.ReactNode
slotA: React.ReactNode
slotB: React.ReactNode
}) {
return (
<div>
{children}
{slotA}
{slotB}
</div>
)
}
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