Unverified Commit d08f4dc0 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Add `experimental.cachedNavigations` feature flag (#90928)

The recent Cached Navigations feature introduced navigation-level
caching into the segment cache, where static and dynamic RSC data from
navigations and initial HTML loads is cached so that repeat visits can
be served instantly. This feature is currently gated behind
`cacheComponents`, meaning it activates for all projects that enable
Cache Components.

This change introduces a new `experimental.cachedNavigations` flag that
independently controls the Cached Navigations behavior. The flag
defaults to `false` so we can investigate potential regressions that the
feature might have introduced without affecting the broader Cache
Components functionality.

The flag requires `cacheComponents` to also be enabled and throws a
configuration error if `cachedNavigations` is set without it. On the
server, the staged rendering paths in `app-render.tsx` (both RSC request
handling and initial HTML rendering) now check `cacheComponents &&
cachedNavigations` before producing staged responses. On the client,
`process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS` is used alongside
`process.env.__NEXT_CACHE_COMPONENTS` for compile-time dead code
elimination in the stream tee (`app-index.tsx`) and the response
processing (`fetch-server-response.ts`).

The cached navigations test suite enables the flag via `next.config.ts`,
and the Cache Components CI jobs export
`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true` to maintain test coverage.
parent 73b44a18
...@@ -813,6 +813,7 @@ jobs: ...@@ -813,6 +813,7 @@ jobs:
# Keep Next.js related env variables in sync with additionalEnv in next-deploy.ts # Keep Next.js related env variables in sync with additionalEnv in next-deploy.ts
afterBuild: | afterBuild: |
export __NEXT_CACHE_COMPONENTS=true export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/deploy-tests-manifest.json,test/cache-components-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="test/deploy-tests-manifest.json,test/cache-components-tests-manifest.json"
export NEXT_E2E_TEST_TIMEOUT=240000 export NEXT_E2E_TEST_TIMEOUT=240000
...@@ -1078,6 +1079,7 @@ jobs: ...@@ -1078,6 +1079,7 @@ jobs:
nodeVersion: 20.9.0 nodeVersion: 20.9.0
afterBuild: | afterBuild: |
export __NEXT_CACHE_COMPONENTS=true export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json"
export IS_WEBPACK_TEST=1 export IS_WEBPACK_TEST=1
...@@ -1108,6 +1110,7 @@ jobs: ...@@ -1108,6 +1110,7 @@ jobs:
with: with:
afterBuild: | afterBuild: |
export __NEXT_CACHE_COMPONENTS=true export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json"
export NEXT_TEST_MODE=dev export NEXT_TEST_MODE=dev
...@@ -1142,6 +1145,7 @@ jobs: ...@@ -1142,6 +1145,7 @@ jobs:
with: with:
afterBuild: | afterBuild: |
export __NEXT_CACHE_COMPONENTS=true export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json"
export NEXT_TEST_MODE=start export NEXT_TEST_MODE=start
......
...@@ -1086,5 +1086,6 @@ ...@@ -1086,5 +1086,6 @@
"1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata", "1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata",
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport", "1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s", "1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body" "1088": "Expected RSC navigation response to have a body",
"1089": "\\`experimental.cachedNavigations\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly."
} }
...@@ -172,6 +172,9 @@ export function getDefineEnv({ ...@@ -172,6 +172,9 @@ export function getDefineEnv({
), ),
'process.env.__NEXT_PPR': isPPREnabled, 'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled, 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(
config.experimental.cachedNavigations
),
'process.env.__NEXT_INSTANT_NAV_TOGGLE': 'process.env.__NEXT_INSTANT_NAV_TOGGLE':
!!config.experimental.instantNavigationDevToolsToggle, !!config.experimental.instantNavigationDevToolsToggle,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
......
...@@ -737,6 +737,9 @@ export async function handler( ...@@ -737,6 +737,9 @@ export async function handler(
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining), prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean(
nextConfig.experimental.cachedNavigations
),
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any), nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins: clientParamParsingOrigins:
......
...@@ -165,6 +165,7 @@ async function requestHandler( ...@@ -165,6 +165,7 @@ async function requestHandler(
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining), prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations),
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any), nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins: clientParamParsingOrigins:
......
...@@ -180,7 +180,10 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -180,7 +180,10 @@ if (process.env.NODE_ENV !== 'production') {
// know if `l` is present until React decodes the payload, so always tee and // know if `l` is present until React decodes the payload, so always tee and
// cancel the clone if not needed. // cancel the clone if not needed.
let initialFlightStreamForCache: ReadableStream<Uint8Array> | null = null let initialFlightStreamForCache: ReadableStream<Uint8Array> | null = null
if (process.env.__NEXT_CACHE_COMPONENTS) { if (
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS
) {
const [forReact, forCache] = readable.tee() const [forReact, forCache] = readable.tee()
readable = forReact readable = forReact
initialFlightStreamForCache = forCache initialFlightStreamForCache = forCache
......
...@@ -328,7 +328,7 @@ export type RSCResponse<T> = { ...@@ -328,7 +328,7 @@ export type RSCResponse<T> = {
type FetchResponseCacheData = { type FetchResponseCacheData = {
isResponsePartial: boolean isResponsePartial: boolean
responseBodyClone: ReadableStream<Uint8Array> responseBodyClone?: ReadableStream<Uint8Array>
} }
/** /**
...@@ -355,9 +355,20 @@ export async function processFetch(response: Response): Promise<{ ...@@ -355,9 +355,20 @@ export async function processFetch(response: Response): Promise<{
} }
const { stream, isPartial } = await stripIsPartialByte(response.body) const { stream, isPartial } = await stripIsPartialByte(response.body)
let responseStream: ReadableStream<Uint8Array>
let cacheData: FetchResponseCacheData
if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {
const [stream1, stream2] = stream.tee() const [stream1, stream2] = stream.tee()
responseStream = stream1
cacheData = { isResponsePartial: isPartial, responseBodyClone: stream2 }
} else {
responseStream = stream
cacheData = { isResponsePartial: isPartial }
}
const strippedResponse = new Response(stream1, { const strippedResponse = new Response(responseStream, {
headers: response.headers, headers: response.headers,
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
...@@ -371,10 +382,7 @@ export async function processFetch(response: Response): Promise<{ ...@@ -371,10 +382,7 @@ export async function processFetch(response: Response): Promise<{
value: response.redirected, value: response.redirected,
}) })
return { return { response: strippedResponse, cacheData }
response: strippedResponse,
cacheData: { isResponsePartial: isPartial, responseBodyClone: stream2 },
}
} }
return { response, cacheData: null } return { response, cacheData: null }
...@@ -398,6 +406,7 @@ export async function resolveStaticStageData< ...@@ -398,6 +406,7 @@ export async function resolveStaticStageData<
): Promise<StaticStageData<T> | null> { ): Promise<StaticStageData<T> | null> {
const { isResponsePartial, responseBodyClone } = cacheData const { isResponsePartial, responseBodyClone } = cacheData
if (responseBodyClone) {
if (!isResponsePartial) { if (!isResponsePartial) {
// Fully static — cache the entire decoded response as-is. // Fully static — cache the entire decoded response as-is.
responseBodyClone.cancel() responseBodyClone.cancel()
...@@ -419,6 +428,7 @@ export async function resolveStaticStageData< ...@@ -419,6 +428,7 @@ export async function resolveStaticStageData<
// No caching — cancel the unused clone. // No caching — cancel the unused clone.
responseBodyClone.cancel() responseBodyClone.cancel()
}
return null return null
} }
......
...@@ -3002,26 +3002,30 @@ export async function processRuntimePrefetchStream( ...@@ -3002,26 +3002,30 @@ export async function processRuntimePrefetchStream(
* response (Flight rows start with a hex digit or ':'). * response (Flight rows start with a hex digit or ':').
* *
* If the first byte is not a recognized marker, the stream is returned intact * If the first byte is not a recognized marker, the stream is returned intact
* and the response is conservatively treated as partial. * and `isPartial` is determined by the cachedNavigations experimental flag.
*/ */
export async function stripIsPartialByte( export async function stripIsPartialByte(
stream: ReadableStream<Uint8Array> stream: ReadableStream<Uint8Array>
): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> { ): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {
// When there is no recognized marker byte, the fallback depends on whether
// Cached Navigations is enabled. When enabled, dynamic navigation responses
// don't have a marker but may contain dynamic holes, so they are treated as
// partial. When disabled, unmarked responses are treated as non-partial.
const defaultIsPartial = !!process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS
const reader = stream.getReader() const reader = stream.getReader()
const { done, value } = await reader.read() const { done, value } = await reader.read()
if (done || !value || value.byteLength === 0) { if (done || !value || value.byteLength === 0) {
return { return {
stream: new ReadableStream({ start: (c) => c.close() }), stream: new ReadableStream({ start: (c) => c.close() }),
isPartial: true, isPartial: defaultIsPartial,
} }
} }
const firstByte = value[0] const firstByte = value[0]
// '#' (0x23) = complete, '~' (0x7e) = partial.
// Only '#' explicitly means non-partial. Everything else (including
// unrecognized bytes) is conservatively treated as partial.
const hasMarker = firstByte === 0x23 || firstByte === 0x7e const hasMarker = firstByte === 0x23 || firstByte === 0x7e
const isPartial = firstByte !== 0x23 const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial
const remainder = hasMarker const remainder = hasMarker
? value.byteLength > 1 ? value.byteLength > 1
......
...@@ -511,6 +511,7 @@ async function exportAppImpl( ...@@ -511,6 +511,7 @@ async function exportAppImpl(
inlineCss: nextConfig.experimental.inlineCss ?? false, inlineCss: nextConfig.experimental.inlineCss ?? false,
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false, prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts, authInterrupts: !!nextConfig.experimental.authInterrupts,
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize nextConfig.experimental.maxPostponedStateSize
), ),
......
...@@ -2043,6 +2043,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -2043,6 +2043,8 @@ async function renderToHTMLOrFlightImpl(
setIsrStatus, setIsrStatus,
} = renderOpts } = renderOpts
const { cachedNavigations } = renderOpts.experimental
// We need to expose the bundled `require` API globally for // We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way. // react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) { if (ComponentMod.__next_app__) {
...@@ -2409,7 +2411,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -2409,7 +2411,7 @@ async function renderToHTMLOrFlightImpl(
createRequestStore, createRequestStore,
fallbackParams fallbackParams
) )
} else if (cacheComponents) { } else if (cacheComponents && cachedNavigations) {
return generateStagedDynamicFlightRenderResult(req, ctx, requestStore) return generateStagedDynamicFlightRenderResult(req, ctx, requestStore)
} else { } else {
return generateDynamicFlightRenderResult(req, ctx, requestStore) return generateDynamicFlightRenderResult(req, ctx, requestStore)
...@@ -2727,6 +2729,8 @@ async function renderToStream( ...@@ -2727,6 +2729,8 @@ async function renderToStream(
cacheComponents, cacheComponents,
} = renderOpts } = renderOpts
const { cachedNavigations } = renderOpts.experimental
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML() createServerInsertedHTML()
const getServerInsertedMetadata = createServerInsertedMetadata(nonce) const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
...@@ -2973,10 +2977,11 @@ async function renderToStream( ...@@ -2973,10 +2977,11 @@ async function renderToStream(
requestId requestId
) )
} }
} else if (cacheComponents) { } else if (cacheComponents && cachedNavigations) {
// Production Cache Components: use staged rendering so the RSC payload // Production Cache Components + Cached Navigations: use staged
// includes the static stage byte length (`l` field), enabling the // rendering so the RSC payload includes the static stage byte length
// client to cache the static subset during hydration. // (`l` field), enabling the client to cache the static subset during
// hydration.
const { renderToReadableStream } = ctx.componentMod const { renderToReadableStream } = ctx.componentMod
const selectStaleTime = createSelectStaleTime(experimental) const selectStaleTime = createSelectStaleTime(experimental)
...@@ -4786,6 +4791,8 @@ async function prerenderToStream( ...@@ -4786,6 +4791,8 @@ async function prerenderToStream(
cacheComponents, cacheComponents,
} = renderOpts } = renderOpts
const { cachedNavigations } = renderOpts.experimental
const allowEmptyStaticShell = const allowEmptyStaticShell =
(renderOpts.allowEmptyStaticShell ?? false) || (renderOpts.allowEmptyStaticShell ?? false) ||
(await isPageAllowedToBlock(tree)) (await isPageAllowedToBlock(tree))
...@@ -5267,8 +5274,11 @@ async function prerenderToStream( ...@@ -5267,8 +5274,11 @@ async function prerenderToStream(
{ is404: res.statusCode === 404 } { is404: res.statusCode === 404 }
) )
const staleTimeIterable = new StaleTimeIterable() let staleTimeIterable: StaleTimeIterable | undefined
if (cachedNavigations) {
staleTimeIterable = new StaleTimeIterable()
finalAttemptRSCPayload.s = staleTimeIterable finalAttemptRSCPayload.s = staleTimeIterable
}
const serverDynamicTracking = createDynamicTrackingState( const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses isDebugDynamicAccesses
...@@ -5297,11 +5307,13 @@ async function prerenderToStream( ...@@ -5297,11 +5307,13 @@ async function prerenderToStream(
varyParamsAccumulator, varyParamsAccumulator,
}) })
if (staleTimeIterable !== undefined) {
trackStaleTime( trackStaleTime(
finalServerPrerenderStore, finalServerPrerenderStore,
staleTimeIterable, staleTimeIterable,
selectStaleTime selectStaleTime
) )
}
let prerenderIsPending = true let prerenderIsPending = true
const finalRSCPrerenderOptions = { const finalRSCPrerenderOptions = {
...@@ -5322,10 +5334,13 @@ async function prerenderToStream( ...@@ -5322,10 +5334,13 @@ async function prerenderToStream(
// We resolve these directly here instead of reading from the work // We resolve these directly here instead of reading from the work
// unit store because this callback runs in a separate task (via // unit store because this callback runs in a separate task (via
// setTimeout) and may not have access to the async storage context. // setTimeout) and may not have access to the async storage context.
await Promise.all([ const pendingFinishes: Promise<void>[] = [
finishStaleTimeTracking(staleTimeIterable),
finishAccumulatingVaryParams(varyParamsAccumulator), finishAccumulatingVaryParams(varyParamsAccumulator),
]) ]
if (staleTimeIterable !== undefined) {
pendingFinishes.push(finishStaleTimeTracking(staleTimeIterable))
}
await Promise.all(pendingFinishes)
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
...@@ -5496,11 +5511,16 @@ async function prerenderToStream( ...@@ -5496,11 +5511,16 @@ async function prerenderToStream(
}) })
metadata.flightData = await streamToBuffer( metadata.flightData = await streamToBuffer(
prependIsPartialByte(reactServerResult.asStream(), serverIsDynamic) cachedNavigations
? prependIsPartialByte(reactServerResult.asStream(), serverIsDynamic)
: reactServerResult.asStream()
) )
// collectSegmentData needs the raw flight data without the marker byte. // collectSegmentData needs the raw flight data without the marker byte.
const flightData = metadata.flightData.subarray(1) const flightData = cachedNavigations
? metadata.flightData.subarray(1)
: metadata.flightData
metadata.segmentData = await collectSegmentData( metadata.segmentData = await collectSegmentData(
flightData, flightData,
finalServerPrerenderStore, finalServerPrerenderStore,
......
...@@ -162,6 +162,7 @@ export interface RenderOptsPartial { ...@@ -162,6 +162,7 @@ export interface RenderOptsPartial {
inlineCss: boolean inlineCss: boolean
prefetchInlining: boolean prefetchInlining: boolean
authInterrupts: boolean authInterrupts: boolean
cachedNavigations: boolean
/** /**
* The maximum size (in bytes) of the postponed state body for PPR resume * The maximum size (in bytes) of the postponed state body for PPR resume
......
...@@ -576,6 +576,8 @@ export default abstract class Server< ...@@ -576,6 +576,8 @@ export default abstract class Server<
prefetchInlining: prefetchInlining:
this.nextConfig.experimental.prefetchInlining ?? false, this.nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts, authInterrupts: !!this.nextConfig.experimental.authInterrupts,
cachedNavigations:
this.nextConfig.experimental.cachedNavigations ?? false,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
this.nextConfig.experimental.maxPostponedStateSize this.nextConfig.experimental.maxPostponedStateSize
), ),
......
...@@ -218,6 +218,7 @@ export const experimentalSchema = { ...@@ -218,6 +218,7 @@ export const experimentalSchema = {
craCompat: z.boolean().optional(), craCompat: z.boolean().optional(),
caseSensitiveRoutes: z.boolean().optional(), caseSensitiveRoutes: z.boolean().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(), clientParamParsingOrigins: z.array(z.string()).optional(),
cachedNavigations: z.boolean().optional(),
dynamicOnHover: z.boolean().optional(), dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(), optimisticRouting: z.boolean().optional(),
varyParams: z.boolean().optional(), varyParams: z.boolean().optional(),
......
...@@ -352,6 +352,7 @@ export interface ExperimentalConfig { ...@@ -352,6 +352,7 @@ export interface ExperimentalConfig {
* rewrites will get the rewrite headers. * rewrites will get the rewrite headers.
*/ */
clientParamParsingOrigins?: string[] clientParamParsingOrigins?: string[]
cachedNavigations?: boolean
dynamicOnHover?: boolean dynamicOnHover?: boolean
optimisticRouting?: boolean optimisticRouting?: boolean
varyParams?: boolean varyParams?: boolean
...@@ -1646,6 +1647,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1646,6 +1647,7 @@ export const defaultConfig = Object.freeze({
linkNoTouchStart: false, linkNoTouchStart: false,
caseSensitiveRoutes: false, caseSensitiveRoutes: false,
clientParamParsingOrigins: undefined, clientParamParsingOrigins: undefined,
cachedNavigations: false,
dynamicOnHover: false, dynamicOnHover: false,
varyParams: false, varyParams: false,
prefetchInlining: false, prefetchInlining: false,
...@@ -1825,6 +1827,7 @@ export interface NextConfigRuntime { ...@@ -1825,6 +1827,7 @@ export interface NextConfigRuntime {
| 'runtimeServerDeploymentId' | 'runtimeServerDeploymentId'
| 'maxPostponedStateSize' | 'maxPostponedStateSize'
| 'devCacheControlNoCache' | 'devCacheControlNoCache'
| 'cachedNavigations'
| 'exposeTestingApiInProductionBuild' | 'exposeTestingApiInProductionBuild'
| 'immutableAssetToken' | 'immutableAssetToken'
> & { > & {
...@@ -1894,6 +1897,7 @@ export function getNextConfigRuntime( ...@@ -1894,6 +1897,7 @@ export function getNextConfigRuntime(
runtimeServerDeploymentId: ex.runtimeServerDeploymentId, runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
maxPostponedStateSize: ex.maxPostponedStateSize, maxPostponedStateSize: ex.maxPostponedStateSize,
devCacheControlNoCache: ex.devCacheControlNoCache, devCacheControlNoCache: ex.devCacheControlNoCache,
cachedNavigations: ex.cachedNavigations,
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild, exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
immutableAssetToken: ex.immutableAssetToken, immutableAssetToken: ex.immutableAssetToken,
......
...@@ -430,6 +430,12 @@ function assignDefaultsAndValidate( ...@@ -430,6 +430,12 @@ function assignDefaultsAndValidate(
) )
} }
if (result.experimental.cachedNavigations && !result.cacheComponents) {
throw new Error(
`\`experimental.cachedNavigations\` requires \`cacheComponents\` to be enabled. Please update your ${configFileName} accordingly.`
)
}
if (result.experimental.ppr) { if (result.experimental.ppr) {
throw new HardDeprecatedConfigError( throw new HardDeprecatedConfigError(
`\`experimental.ppr\` has been merged into \`cacheComponents\`. The Partial Prerendering feature is still available, but is now enabled via \`cacheComponents\`. Please update your ${configFileName} accordingly.` `\`experimental.ppr\` has been merged into \`cacheComponents\`. The Partial Prerendering feature is still available, but is now enabled via \`cacheComponents\`. Please update your ${configFileName} accordingly.`
...@@ -1939,6 +1945,25 @@ function enforceExperimentalFeatures( ...@@ -1939,6 +1945,25 @@ function enforceExperimentalFeatures(
config.cacheComponents = true config.cacheComponents = true
} }
// TODO: Remove this once cachedNavigations is the default.
if (
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS === 'true' &&
// We do respect an explicit value in the user config.
(config.experimental.cachedNavigations === undefined ||
(isDefaultConfig && !config.experimental.cachedNavigations))
) {
config.experimental.cachedNavigations = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'cachedNavigations',
true,
'enabled by `__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS`'
)
}
}
// TODO: Remove this once appNewScrollHandler is the default. // TODO: Remove this once appNewScrollHandler is the default.
if ( if (
process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER === 'true' && process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER === 'true' &&
......
...@@ -4,6 +4,7 @@ const nextConfig: NextConfig = { ...@@ -4,6 +4,7 @@ const nextConfig: NextConfig = {
cacheComponents: true, cacheComponents: true,
productionBrowserSourceMaps: true, productionBrowserSourceMaps: true,
experimental: { experimental: {
cachedNavigations: true,
exposeTestingApiInProductionBuild: true, exposeTestingApiInProductionBuild: true,
}, },
} }
......
...@@ -445,6 +445,9 @@ export class NextInstance { ...@@ -445,6 +445,9 @@ export class NextInstance {
if (process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS) { if (process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS) {
process.env.__NEXT_CACHE_COMPONENTS = process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS process.env.__NEXT_CACHE_COMPONENTS = process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS
} }
if (process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHED_NAVIGATIONS) {
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS = process.env.NEXT_PRIVATE_EXPERIMENTAL_CACHED_NAVIGATIONS
}
if (process.env.NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER) { if (process.env.NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER) {
process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER = process.env.NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER = process.env.NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER
} }
......
...@@ -355,6 +355,11 @@ export class NextDeployInstance extends NextInstance { ...@@ -355,6 +355,11 @@ export class NextDeployInstance extends NextInstance {
`NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS=${process.env.__NEXT_CACHE_COMPONENTS}` `NEXT_PRIVATE_EXPERIMENTAL_CACHE_COMPONENTS=${process.env.__NEXT_CACHE_COMPONENTS}`
) )
} }
if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {
additionalEnv.push(
`NEXT_PRIVATE_EXPERIMENTAL_CACHED_NAVIGATIONS=${process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS}`
)
}
if (process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER) { if (process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER) {
additionalEnv.push( additionalEnv.push(
`NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=${process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER}` `NEXT_PRIVATE_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=${process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER}`
......
...@@ -21,21 +21,24 @@ describe('build-output-prerender', () => { ...@@ -21,21 +21,24 @@ describe('build-output-prerender', () => {
"▲ Next.js x.y.z (Turbopack) "▲ Next.js x.y.z (Turbopack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} else if (isRspack) { } else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack) "▲ Next.js x.y.z (Rspack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack) "▲ Next.js x.y.z (webpack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} }
} else { } else {
...@@ -115,6 +118,7 @@ describe('build-output-prerender', () => { ...@@ -115,6 +118,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`) ✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)" ⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
...@@ -127,6 +131,7 @@ describe('build-output-prerender', () => { ...@@ -127,6 +131,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`) ⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
...@@ -139,6 +144,7 @@ describe('build-output-prerender', () => { ...@@ -139,6 +144,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`) ⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
...@@ -265,21 +271,24 @@ describe('build-output-prerender', () => { ...@@ -265,21 +271,24 @@ describe('build-output-prerender', () => {
"▲ Next.js x.y.z (Turbopack) "▲ Next.js x.y.z (Turbopack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} else if (isRspack) { } else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack) "▲ Next.js x.y.z (Rspack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack) "▲ Next.js x.y.z (webpack)
- Cache Components enabled - Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)" ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)"
`) `)
} }
} else { } else {
...@@ -325,6 +334,7 @@ describe('build-output-prerender', () => { ...@@ -325,6 +334,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`) ✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)" ⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
...@@ -337,6 +347,7 @@ describe('build-output-prerender', () => { ...@@ -337,6 +347,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`) ⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
...@@ -349,6 +360,7 @@ describe('build-output-prerender', () => { ...@@ -349,6 +360,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution): - Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`) ✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`) ⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
......
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