Unverified Commit 59ad3de6 authored by Josh Story's avatar Josh Story Committed by GitHub

Preserve closed-parameter restrictions in client route prediction (#98889)

## Summary

Preserve the restrictions of `dynamicParams = false` in client route
prediction, independently of the proposed parameter-matching API.

For `/products/[slug]` with only `allowed` generated during the build,
learning `/products/allowed` must not imply that `/products/rejected`
exists. This remains true when the page never reads `slug`. The
transport-tree builder now attaches `PrefetchHint.IsClosedParam` to the
affected dynamic node, rather than putting a route-level bit on the
response root or copying it to every prefetch node. Live rendering,
error trees, and prefetch-hint collection preserve that placement.

Legacy `dynamicParams = false` closes the entire parameter tuple. For
`/catalog/[lang]/products/[slug]/details`, both `[lang]` and `[slug]`
receive the hint; the static segments do not. Shared ancestors refresh
their hints even when their UI is reused: navigating between open and
closed pages under the same `[slug]` must add or clear the restriction.

Client behavior remains conservative: optimistic route prediction
declines a tree containing any closed parameter and asks the server to
resolve the destination. Existing apps combining `dynamicParams = false`
with `experimental.optimisticRouting` therefore lose prediction for
those routes. Sending allowed parameter values to the client and
predicting valid destinations from that list is future work, not part of
this change.

This PR is an independent prerequisite extracted from #97393. It does
not enable Cache Components, introduce parameter-matching configuration,
or change which parameter values are allowed. The later API layer
supplies exact closed-parameter names for routes with a closed prefix
and an open suffix.

## Verification

- The legacy routing/navigation fixture runs with Cache Components
disabled. Revised node-placement assertions fail against the old
response-root representation. The shared-sibling navigation test also
reproduced stale hints before the skipped-ancestor refresh was added.
- Initial documents and live client navigations with `prefetch={false}`
place the hint on `[slug]`; open routes carry no closure hint. A nested
legacy route marks both dynamic parameters, and open/closed sibling
navigation updates a reused ancestor.
- Five tests pass in development with both Turbopack and Webpack. The
three existing prefetch-dependent scenarios retain their production-only
gates; all eight tests pass in production with both bundlers.
- The seven production scenarios present before adding shared-sibling
navigation also passed with optimistic routing disabled in the Webpack
axis-A configuration.
- Existing config and transport-tree helper unit suites pass (22 tests
and one snapshot), and repository TypeScript checks pass.
- The eight-test legacy fixture also passes on the integrated API head.

An exploratory dev run of the combined routing-404 scenario encountered
an intermittent Turbopack `NoFallbackError`/500; a subsequent run
returned the expected 404. This PR does not fix that observation or
claim dev coverage for that production-only scenario.

<!-- NEXT_JS_LLM -->
parent 75b9f201
...@@ -155,7 +155,10 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime' ...@@ -155,7 +155,10 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc' import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { installBindings } from './swc/install-bindings' import { installBindings } from './swc/install-bindings'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import {
getNamedRouteRegex,
getRouteRegex,
} from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir' import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins' import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { import {
...@@ -3178,6 +3181,13 @@ export default async function build( ...@@ -3178,6 +3181,13 @@ export default async function build(
sortedStaticPaths.forEach(([originalAppPath, routes]) => { sortedStaticPaths.forEach(([originalAppPath, routes]) => {
const appConfig = appDefaultConfigs.get(originalAppPath) const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error' const isDynamicError = appConfig?.dynamic === 'error'
// Legacy dynamicParams=false closes the entire route tuple.
const notFoundParams =
fallbackModes.get(originalAppPath) === FallbackMode.NOT_FOUND
? Object.keys(
getRouteRegex(normalizeAppPath(originalAppPath)).groups
)
: undefined
const isRoutePPREnabled: boolean = appConfig const isRoutePPREnabled: boolean = appConfig
? isAppCacheComponentsEnabled ? isAppCacheComponentsEnabled
...@@ -3205,6 +3215,7 @@ export default async function build( ...@@ -3205,6 +3215,7 @@ export default async function build(
page: originalAppPath, page: originalAppPath,
_ssgPath: route.encodedPathname, _ssgPath: route.encodedPathname,
_fallbackRouteParams: route.fallbackRouteParams, _fallbackRouteParams: route.fallbackRouteParams,
_notFoundParams: notFoundParams,
_isDynamicError: isDynamicError, _isDynamicError: isDynamicError,
_isAppDir: true, _isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled, _isRoutePPREnabled: isRoutePPREnabled,
......
...@@ -42,6 +42,7 @@ import { ...@@ -42,6 +42,7 @@ import {
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' } import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' }
import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' } import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' }
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' } import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' }
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app' with { 'turbopack-transition': 'next-server-utility' }
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' } import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' }
import { import {
RSC_HEADER, RSC_HEADER,
...@@ -194,6 +195,13 @@ export function createAppPageEntrypoint({ ...@@ -194,6 +195,13 @@ export function createAppPageEntrypoint({
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
// The legacy prerender manifest says whether unmatched values return 404,
// but does not list all of the route's parameter names. Read them from the
// route pattern once, since the names do not depend on the request.
const routeParamNames = parseNormalizedAppRoute(
normalizedSrcPage
).dynamicSegments.map((segment) => segment.param.paramName)
async function handler( async function handler(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -906,6 +914,15 @@ export function createAppPageEntrypoint({ ...@@ -906,6 +914,15 @@ export function createAppPageEntrypoint({
multiZoneDraftMode, multiZoneDraftMode,
prefetchHints: prefetchHintsManifest, prefetchHints: prefetchHintsManifest,
// With dynamicParams = false, every parameter is restricted to the
// paths generated at build time. Advertise this even for allowed
// URLs. Read the current manifest here because dev updates it as
// routes compile.
notFoundParams:
prerenderManifest.dynamicRoutes[normalizedSrcPage]?.fallback ===
false
? routeParamNames
: undefined,
incrementalCache, incrementalCache,
cacheLifeProfiles: nextConfig.cacheLife, cacheLifeProfiles: nextConfig.cacheLife,
staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout, staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,
......
...@@ -765,6 +765,16 @@ export function matchKnownRoute( ...@@ -765,6 +765,16 @@ export function matchKnownRoute(
return null return null
} }
// Closed parameters affect whether the route exists, even when none of its
// components read them. Resolve the target URL on the server instead of
// combining a predicted tree with UI cached for an allowed parameter value.
if (
pattern.tree.prefetchHints &
(PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)
) {
return null
}
// "Reify" the pattern: clone the template tree with concrete param values. // "Reify" the pattern: clone the template tree with concrete param values.
// This substitutes resolved params (e.g., slug: "hello") into dynamic // This substitutes resolved params (e.g., slug: "hello") into dynamic
// segments and recomputes vary paths for correct segment cache keying. // segments and recomputes vary paths for correct segment cache keying.
......
...@@ -102,6 +102,8 @@ async function exportPageImpl( ...@@ -102,6 +102,8 @@ async function exportPageImpl(
// The parameters that are currently unknown. // The parameters that are currently unknown.
_fallbackRouteParams = [], _fallbackRouteParams = [],
_notFoundParams: notFoundParams,
// Check if this is an `app/` page. // Check if this is an `app/` page.
_isAppDir: isAppDir = false, _isAppDir: isAppDir = false,
...@@ -279,6 +281,7 @@ async function exportPageImpl( ...@@ -279,6 +281,7 @@ async function exportPageImpl(
allowEmptyStaticShell, allowEmptyStaticShell,
runInstantValidation, runInstantValidation,
isFallbackUpgradeable, isFallbackUpgradeable,
notFoundParams,
experimental: { experimental: {
...commonRenderOpts.experimental, ...commonRenderOpts.experimental,
isRoutePPREnabled, isRoutePPREnabled,
......
...@@ -2398,7 +2398,8 @@ async function getErrorRSCPayload( ...@@ -2398,7 +2398,8 @@ async function getErrorRSCPayload(
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
Boolean(ctx.renderOpts.partialPrefetching), Boolean(ctx.renderOpts.partialPrefetching),
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query,
ctx.renderOpts.notFoundParams
) )
// Attach the error shell as the root's render output. Vary params are not // Attach the error shell as the root's render output. Vary params are not
// tracked for error pages. // tracked for error pages.
......
...@@ -601,6 +601,7 @@ async function createComponentTreeInternal( ...@@ -601,6 +601,7 @@ async function createComponentTreeInternal(
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query, query,
ctx.renderOpts.notFoundParams,
rootLayoutIncludedAtThisLevelOrAbove rootLayoutIncludedAtThisLevelOrAbove
) )
} else { } else {
...@@ -741,7 +742,8 @@ async function createComponentTreeInternal( ...@@ -741,7 +742,8 @@ async function createComponentTreeInternal(
prefetchInliningEnabled, prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
!rootLayoutIncluded !rootLayoutIncluded,
ctx.renderOpts.notFoundParams
) )
// Convert the parallel route map into an object after all promises have been resolved. // Convert the parallel route map into an object after all promises have been resolved.
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
import type { GetDynamicParamFromSegment } from './app-render' import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment' import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param'
export type MissingPrefetchHintPolicy = export type MissingPrefetchHintPolicy =
| 'mark-stale' | 'mark-stale'
...@@ -64,7 +65,8 @@ export async function computeSegmentPrefetchHints( ...@@ -64,7 +65,8 @@ export async function computeSegmentPrefetchHints(
partialPrefetching: boolean, partialPrefetching: boolean,
// Whether this segment is at or above the root layout (no layout was found // Whether this segment is at or above the root layout (no layout was found
// above it). // above it).
isRootLayoutOrAbove: boolean isRootLayoutOrAbove: boolean,
notFoundParams: readonly string[] | undefined
): Promise<number> { ): Promise<number> {
const { layout, loading, page } = loaderTree[2] const { layout, loading, page } = loaderTree[2]
...@@ -119,6 +121,13 @@ export async function computeSegmentPrefetchHints( ...@@ -119,6 +121,13 @@ export async function computeSegmentPrefetchHints(
prefetchHints |= PrefetchHint.IsRootLayoutOrAbove prefetchHints |= PrefetchHint.IsRootLayoutOrAbove
} }
if (notFoundParams?.length) {
const param = getSegmentParam(loaderTree[0])
if (param !== null && notFoundParams.includes(param.paramName)) {
prefetchHints |= PrefetchHint.IsClosedParam
}
}
if (instantConfig === false) { if (instantConfig === false) {
// The segment explicitly opts out of Partial Prefetching. We don't change // The segment explicitly opts out of Partial Prefetching. We don't change
// the prefetch behavior, but we record it so the dev-time // the prefetch behavior, but we record it so the dev-time
...@@ -160,7 +169,8 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -160,7 +169,8 @@ async function createTransportTreeFromLoaderTreeImpl(
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
didFindRootLayout: boolean didFindRootLayout: boolean,
notFoundParams: readonly string[] | undefined
): Promise<PartialTransportNode> { ): Promise<PartialTransportNode> {
const [segment, parallelRoutes, { layout }] = loaderTree const [segment, parallelRoutes, { layout }] = loaderTree
const dynamicParam = getDynamicParamFromSegment(loaderTree) const dynamicParam = getDynamicParamFromSegment(loaderTree)
...@@ -172,7 +182,8 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -172,7 +182,8 @@ async function createTransportTreeFromLoaderTreeImpl(
prefetchInliningEnabled, prefetchInliningEnabled,
missingPrefetchHintPolicy, missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
!didFindRootLayout !didFindRootLayout,
notFoundParams
) )
if (!didFindRootLayout && typeof layout !== 'undefined') { if (!didFindRootLayout && typeof layout !== 'undefined') {
...@@ -195,7 +206,8 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -195,7 +206,8 @@ async function createTransportTreeFromLoaderTreeImpl(
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout,
notFoundParams
) )
// Propagate subtree flags from children // Propagate subtree flags from children
if (child.h !== undefined) { if (child.h !== undefined) {
...@@ -238,6 +250,7 @@ export async function createTransportTreeFromLoaderTree( ...@@ -238,6 +250,7 @@ export async function createTransportTreeFromLoaderTree(
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
notFoundParams: readonly string[] | undefined,
// Whether a root layout was already found above this loader tree slice, so a // Whether a root layout was already found above this loader tree slice, so a
// slice that starts below the root layout doesn't mark a sub-layout as the // slice that starts below the root layout doesn't mark a sub-layout as the
// root layout. // root layout.
...@@ -252,7 +265,8 @@ export async function createTransportTreeFromLoaderTree( ...@@ -252,7 +265,8 @@ export async function createTransportTreeFromLoaderTree(
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout,
notFoundParams
) )
} }
...@@ -268,7 +282,8 @@ export async function createFullTransportTreeFromLoaderTree( ...@@ -268,7 +282,8 @@ export async function createFullTransportTreeFromLoaderTree(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any searchParams: any,
notFoundParams: readonly string[] | undefined
): Promise<FullTransportNode> { ): Promise<FullTransportNode> {
// With emitSkippedData, every node carries data, which is what // With emitSkippedData, every node carries data, which is what
// FullTransportNode requires. TypeScript can't see through the flag, // FullTransportNode requires. TypeScript can't see through the flag,
...@@ -282,7 +297,8 @@ export async function createFullTransportTreeFromLoaderTree( ...@@ -282,7 +297,8 @@ export async function createFullTransportTreeFromLoaderTree(
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
false false,
notFoundParams
) as Promise<FullTransportNode> ) as Promise<FullTransportNode>
} }
...@@ -297,6 +313,7 @@ export async function createRouteTreePrefetch( ...@@ -297,6 +313,7 @@ export async function createRouteTreePrefetch(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
notFoundParams: readonly string[] | undefined,
// See note on createTransportTreeFromLoaderTree's didFindRootLayout. // See note on createTransportTreeFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false didFindRootLayout: boolean = false
): Promise<PartialTransportNode> { ): Promise<PartialTransportNode> {
...@@ -313,6 +330,7 @@ export async function createRouteTreePrefetch( ...@@ -313,6 +330,7 @@ export async function createRouteTreePrefetch(
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout,
notFoundParams
) )
} }
...@@ -221,6 +221,9 @@ export interface RenderOptsPartial { ...@@ -221,6 +221,9 @@ export interface RenderOptsPartial {
*/ */
prefetchHints?: Record<string, PrefetchHints> prefetchHints?: Record<string, PrefetchHints>
/** Parameters whose novel values are rejected by routing. */
notFoundParams?: readonly string[]
/** /**
* When true, the page is prerendered as a fallback shell, while allowing any * When true, the page is prerendered as a fallback shell, while allowing any
* dynamic accesses to result in an empty shell. This is the case when there * dynamic accesses to result in an empty shell. This is the case when there
......
...@@ -15,6 +15,7 @@ import type { LoaderTree } from '../lib/app-dir-module' ...@@ -15,6 +15,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import { getLinkAndScriptTags } from './get-css-inlined-link-tags' import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import { getPreloadableFonts } from './get-preloadable-fonts' import { getPreloadableFonts } from './get-preloadable-fonts'
import { import {
computeSegmentPrefetchHints,
createTransportTreeFromLoaderTree, createTransportTreeFromLoaderTree,
createRouteTreePrefetch, createRouteTreePrefetch,
} from './create-transport-tree-from-loader-tree' } from './create-transport-tree-from-loader-tree'
...@@ -171,6 +172,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -171,6 +172,7 @@ export async function walkTreeWithFlightRouterState({
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded rootLayoutIncluded
) )
: await createTransportTreeFromLoaderTree( : await createTransportTreeFromLoaderTree(
...@@ -181,6 +183,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -181,6 +183,7 @@ export async function walkTreeWithFlightRouterState({
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query, query,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded rootLayoutIncluded
) )
...@@ -201,7 +204,8 @@ export async function walkTreeWithFlightRouterState({ ...@@ -201,7 +204,8 @@ export async function walkTreeWithFlightRouterState({
prefetchInliningEnabled, prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment getDynamicParamFromSegment,
ctx.renderOpts.notFoundParams
) )
: await createTransportTreeFromLoaderTree( : await createTransportTreeFromLoaderTree(
loaderTreeToFilter, loaderTreeToFilter,
...@@ -211,6 +215,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -211,6 +215,7 @@ export async function walkTreeWithFlightRouterState({
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query, query,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded rootLayoutIncluded
) )
return { return {
...@@ -322,6 +327,17 @@ export async function walkTreeWithFlightRouterState({ ...@@ -322,6 +327,17 @@ export async function walkTreeWithFlightRouterState({
// rendered subtrees, so the client is expected to already have it. // rendered subtrees, so the client is expected to already have it.
tree: { tree: {
s: segmentToTransportSegment(actualSegment), s: segmentToTransportSegment(actualSegment),
// The UI is shared, but route-specific restrictions may have changed
// (e.g. an open sibling navigating to a dynamicParams=false page).
h: await computeSegmentPrefetchHints(
loaderTreeToFilter,
hintTree,
prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy,
partialPrefetching,
!rootLayoutIncluded,
ctx.renderOpts.notFoundParams
),
d: createSkippedSegmentData(), d: createSkippedSegmentData(),
c: children, c: children,
}, },
......
...@@ -39,6 +39,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record( ...@@ -39,6 +39,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
// private optional properties // private optional properties
_fallbackRouteParams: z.array(z.any()).optional(), _fallbackRouteParams: z.array(z.any()).optional(),
_notFoundParams: z.array(z.string()).optional(),
_isAppDir: z.boolean().optional(), _isAppDir: z.boolean().optional(),
_isDynamicError: z.boolean().optional(), _isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(), _isRoutePPREnabled: z.boolean().optional(),
......
...@@ -1645,6 +1645,9 @@ export type ExportPathMap = { ...@@ -1645,6 +1645,9 @@ export type ExportPathMap = {
*/ */
_fallbackRouteParams?: readonly FallbackRouteParam[] _fallbackRouteParams?: readonly FallbackRouteParam[]
/** Parameters whose novel values are rejected by routing. @internal */
_notFoundParams?: readonly string[]
/** /**
* @internal * @internal
*/ */
......
...@@ -278,6 +278,14 @@ export const enum PrefetchHint { ...@@ -278,6 +278,14 @@ export const enum PrefetchHint {
// fallbacks — simply never carry it.) Set on every node of the tree, but // fallbacks — simply never carry it.) Set on every node of the tree, but
// does not propagate. // does not propagate.
ShouldAttemptStaticPrefetch = 0b100000000000000, ShouldAttemptStaticPrefetch = 0b100000000000000,
// This dynamic segment only accepts build-time parameter values. Kept on
// the affected node, without propagating or copying it to other segments.
// Until the client knows the allowed values, any such node prevents route
// prediction, even when the route's components never read the parameter.
IsClosedParam = 0b1000000000000000,
// A descendant segment (but not this one) has a closed parameter. Propagates
// upward so route prediction can check the root instead of walking the tree.
SubtreeHasClosedParams = 0b10000000000000000,
} }
/** /**
...@@ -309,7 +317,8 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled ...@@ -309,7 +317,8 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const SubtreePrefetchHints = export const SubtreePrefetchHints =
PrefetchHint.SubtreeHasPartialPrefetching | PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasLoadingBoundary | PrefetchHint.SubtreeHasLoadingBoundary |
PrefetchHint.SubtreeHasInstantFalse PrefetchHint.SubtreeHasInstantFalse |
PrefetchHint.SubtreeHasClosedParams
/** /**
* Folds a child segment's prefetch hints into its parent's, propagating the * Folds a child segment's prefetch hints into its parent's, propagating the
...@@ -344,6 +353,12 @@ export function propagateSubtreeBits( ...@@ -344,6 +353,12 @@ export function propagateSubtreeBits(
if (childHints & PrefetchHint.SubtreeHasInstantFalse) { if (childHints & PrefetchHint.SubtreeHasInstantFalse) {
parentHints |= PrefetchHint.SubtreeHasInstantFalse parentHints |= PrefetchHint.SubtreeHasInstantFalse
} }
if (
childHints &
(PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)
) {
parentHints |= PrefetchHint.SubtreeHasClosedParams
}
return parentHints return parentHints
} }
......
export const dynamicParams = false
export function generateStaticParams() {
return [{ lang: 'en', slug: 'allowed' }]
}
export default function Page() {
return <p id="catalog-page">Allowed catalog page</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p id="root-not-found">Route not found</p>
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="open-product-page">Open product page</p>
<Link href="/products/allowed" prefetch={false} id="navigate-allowed">
Navigate to an allowed product without prefetching
</Link>
</>
)
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Prefetch closed parameters</h1>
<LinkAccordion href="/products/allowed">Allowed product</LinkAccordion>
<LinkAccordion href="/products/rejected">Rejected product</LinkAccordion>
<Link href="/products/rejected" prefetch={false} id="navigate-rejected">
Navigate without prefetching
</Link>
</main>
)
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return <p id="product-page">Allowed product page</p>
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<section id="products-layout">
<h1>Product catalog</h1>
{children}
</section>
)
}
export default function NotFound() {
return <p id="nested-not-found">Product not found</p>
}
import Link from 'next/link'
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="shared-closed-page">Closed sibling</p>
<Link id="open-sibling" href="/shared/allowed/open" prefetch={false}>
Open sibling
</Link>
</>
)
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="shared-open-page">Open sibling</p>
<Link id="closed-sibling" href="/shared/allowed/closed" prefetch={false}>
Closed sibling
</Link>
</>
)
}
'use client'
import Link from 'next/link'
import { useState, type ReactNode } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<div>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? <Link href={href}>{children}</Link> : children}
</div>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
partialPrefetching: false,
experimental: {
// Keep this legacy fixture independent of the CC CI job's defaults.
cachedNavigations: false,
optimisticRouting: process.env.__NEXT_TEST_AXIS !== 'A',
varyParams: true,
prefetchInlining: true,
},
}
export default nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment