Unverified Commit d5d747e9 authored by Josh Story's avatar Josh Story Committed by GitHub

Add unstable parameter matching APIs (#97393)

## Summary

Let Cache Components applications configure parameter matching
separately from build-time prerenders. `generateStaticParams` continues
to supply concrete examples; the new `unstable_paramMatching` and
`unstable_generateParamMatching` exports control whether a novel value
returns 404, blocks on generation, receives a fallback shell, or stays
dynamic.

With `cacheComponents: true`:

```ts
// app/[lang]/layout.tsx
export const unstable_paramMatching = { lang: 'not-found' }

// app/[lang]/catalog/[top]/items/[bottom]/page.tsx
export const unstable_paramMatching = {
  top: 'blocking',
  bottom: 'fallback',
}

export function generateStaticParams() {
  return [{ lang: 'en', top: 't1', bottom: 'b1' }]
}
```

This prerenders `/en/catalog/t1/items/b1`. A language other than `en`
returns 404. On a cache miss, `/en/catalog/t2/items/b2` blocks on
generation, while `/en/catalog/t1/items/b2` can receive fallback UI
immediately. `dynamic` keeps a parameter out of prerenders.

Alternatively, `export async function unstable_generateParamMatching()`
returns the same partial object. It takes no arguments and runs
independently of `generateStaticParams`, once per module within each
route evaluation. Public `use cache` helpers are supported. No
additional configuration flag is required, and `ParamMatching` from
`next` provides optional strict typing.

Policies merge from layouts toward pages, with descendants overriding
only supplied keys:

- A module can configure parameters at or above its segment. Explicit
modes must follow URL order: `not-found → blocking → fallback →
dynamic`.
- A `not-found` parameter requires every preceding parameter to be
explicitly `not-found`, too. Every route or parallel branch sharing that
parameter definition must agree.
- Unconfigured parameters retain inference. An unconfigured tail without
examples stays dynamic; explicitly dynamic parameters cannot be included
in prerenders.
- Shell validation follows explicit fallback boundaries instead of
silently replacing them with blocking behavior; `instant = false` opts
out of that validation. With these APIs, `output: 'export'` requires all
parameters to be explicitly `not-found`.
- `unstable_ensureStatic = 'navigation'` allows `blocking` and
`not-found`, but rejects effective `fallback` and `dynamic` policies in
both builds and development. It still requires complete
`generateStaticParams` examples and fully static server output, even
with `instant = false`. Supporting fallbacks for fully static
navigations is deferred to a follow-up.

Runtime admission, cache regeneration, and client route discovery
preserve those boundaries. Adapter output uses the existing routing
contract, including prefixed query keys for root fallbacks.

## Verification

- Unit and integration coverage for policy merging, validation,
generated types, shell selection, blocking/fallback behavior,
navigation, parameter encoding, revalidation, and root-cache isolation.
- Real fixtures cover direct, inherited, generated, and parallel-slot
combinations with `ensureStatic`, including valid overrides, missing
examples, dynamic-data errors, and preserved closed prefixes. Both
bundlers and both Partial Prefetching settings are covered in
build/start and dev.
- Existing `ensure-static-navigation` build/dev validation and
`ensure-static-navigation-runtime` production suites pass without
changing their fixtures or validation implementation.
- Routing, generator, and root-parameter fixtures have passed real
adapter deployment tests in both ordinary and Cache Components jobs.
Local adapter-output assertions separately check the root-fallback query
contract.
- [ ] Confirm cold open-suffix requests and revalidation in a deployment
known to use grouped functions, and verify rejected prefixes do not
invoke a function or consult ISR. Passing HTTP assertions alone does not
establish these properties.

<!-- NEXT_JS_LLM -->
parent d9831527
......@@ -1259,6 +1259,15 @@ export async function handleBuildComplete({
return parentOutput
}
const sourcesWithOpenFallbacks = new Set<string>()
for (const [pathname, route] of Object.entries(
prerenderManifest.dynamicRoutes
)) {
if (route.fallback !== false) {
sourcesWithOpenFallbacks.add(route.fallbackSourceRoute ?? pathname)
}
}
const {
prefetchSegmentDirSuffix,
prefetchSegmentSuffix,
......@@ -1630,7 +1639,14 @@ export async function handleBuildComplete({
}
: undefined,
parentFallbackMode: srcRouteInfo?.fallback,
// This describes the whole source page, not just its least-specific
// matcher. A closed prefix with an open suffix must remain callable
// for paths that weren't rendered at build time.
parentFallbackMode:
srcRouteInfo?.fallback === false &&
sourcesWithOpenFallbacks.has(srcRoute)
? undefined
: srcRouteInfo?.fallback,
fallback:
!isNotFoundTrue || (isNotFoundTrue && hasStatic404)
......@@ -1799,7 +1815,9 @@ export async function handleBuildComplete({
// present and able to be served.
if (typeof fallback === 'string') {
if (fallbackRootParams && fallbackRootParams.length > 0) {
htmlAllowQuery = fallbackRootParams as string[]
htmlAllowQuery = fallbackRootParams.map(
(paramName) => `${NEXT_QUERY_PARAM_PREFIX}${paramName}`
)
}
// We additionally vary based on if there's a postponed prerender
......
......@@ -48,7 +48,7 @@ import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-pat
import { isProxyFile } from '../utils'
const PARSE_PATTERN =
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|unstable_paramMatching|unstable_generateParamMatching|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
export type ProxyMatcher = {
regexp: string
......@@ -180,6 +180,8 @@ function checkExports(
getServerSideProps?: boolean
generateImageMetadata?: boolean
generateSitemaps?: boolean
paramMatching?: boolean
generateParamMatching?: boolean
generateStaticParams?: boolean
directives?: Set<string>
exports?: Set<string>
......@@ -189,6 +191,8 @@ function checkExports(
'getServerSideProps',
'generateImageMetadata',
'generateSitemaps',
'unstable_paramMatching',
'unstable_generateParamMatching',
'generateStaticParams',
])
if (!Array.isArray(ast?.body)) {
......@@ -200,6 +204,8 @@ function checkExports(
let getServerSideProps: boolean = false
let generateImageMetadata: boolean = false
let generateSitemaps: boolean = false
let paramMatching = false
let generateParamMatching = false
let generateStaticParams = false
let exports = new Set<string>()
let directives = new Set<string>()
......@@ -244,6 +250,10 @@ function checkExports(
getStaticProps = id === 'getStaticProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
if (id === 'unstable_paramMatching') paramMatching = true
if (id === 'unstable_generateParamMatching') {
generateParamMatching = true
}
generateStaticParams = id === 'generateStaticParams'
}
......@@ -257,6 +267,10 @@ function checkExports(
getStaticProps = id === 'getStaticProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
if (id === 'unstable_paramMatching') paramMatching = true
if (id === 'unstable_generateParamMatching') {
generateParamMatching = true
}
generateStaticParams = id === 'generateStaticParams'
}
}
......@@ -281,6 +295,15 @@ function checkExports(
if (!generateSitemaps && value === 'generateSitemaps') {
generateSitemaps = true
}
if (!paramMatching && value === 'unstable_paramMatching') {
paramMatching = true
}
if (
!generateParamMatching &&
value === 'unstable_generateParamMatching'
) {
generateParamMatching = true
}
if (!generateStaticParams && value === 'generateStaticParams') {
generateStaticParams = true
}
......@@ -301,6 +324,8 @@ function checkExports(
getServerSideProps,
generateImageMetadata,
generateSitemaps,
paramMatching,
generateParamMatching,
generateStaticParams,
directives,
exports,
......@@ -647,6 +672,8 @@ export async function getAppPageStaticInfo({
})
const {
paramMatching,
generateParamMatching,
generateStaticParams,
generateImageMetadata,
generateSitemaps,
......@@ -678,6 +705,32 @@ export async function getAppPageStaticInfo({
const route = normalizeAppPath(page)
const config = parseAppSegmentConfig(exportedConfig, route)
const hasParamMatching = paramMatching || generateParamMatching
if (paramMatching && generateParamMatching) {
throw new Error(
`Page "${page}" cannot export both \`unstable_paramMatching\` and \`unstable_generateParamMatching\`.`
)
}
if (hasParamMatching && /\/route\.[^/]+$/.test(pageFilePath)) {
throw new Error(
`Route "${page}" cannot export parameter matching. It is only supported in layouts and pages.`
)
}
if (isEdgeRuntime(config.runtime) && hasParamMatching) {
throw new Error(
`Page "${page}" cannot use both \`export const runtime = 'edge'\` and parameter matching.`
)
}
if (directives?.has('client') && hasParamMatching) {
throw new Error(
`Page "${page}" cannot use both "use client" and a parameter matching export.`
)
}
// Prevent edge runtime and generateStaticParams in the same file.
if (isEdgeRuntime(config.runtime) && generateStaticParams) {
throw new Error(
......
......@@ -137,6 +137,7 @@ import { writeAnalyzeSnapshot } from './analyze/snapshot'
import { writeRouteBundleStats } from './route-bundle-stats'
import {
detectConflictingPaths,
printPrerenderMatchers,
printCustomRoutes,
printTreeView,
copyTracedFiles,
......@@ -154,6 +155,8 @@ import type {
PrerenderedRoute,
} from './static-paths/types'
import type { AppSegmentConfig } from './segment-config/app/app-segment-config'
import type { ParamMatching } from './segment-config/app/app-segments'
import { validateParamMatchingCoherence } from './static-paths/param-matching'
import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import isError from '../lib/is-error'
......@@ -349,6 +352,18 @@ export interface DynamicPrerenderManifestRoute
experimentalBypassFor?: RouteHas[]
fallback: Fallback
/**
* A configured blocking policy must not be replaced by on-demand fallback
* shell generation when Partial Prefetching is enabled.
*/
isExplicitlyBlocking?: true
/**
* Parameter-matching restrictions used by Next.js when constructing client
* route trees. Unlike legacy fallback=false, only these parameters are closed.
*/
notFoundParams?: readonly string[]
/**
* The unresolved fallback route params that can still be specialized into a
* more specific prerendered shell because their segments export
......@@ -2259,6 +2274,7 @@ export default async function build(
const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>()
const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>()
const paramMatchingByRoute = new Map<string, ParamMatching | undefined>()
const appNormalizedPaths = new Map<string, string>()
const fallbackModes = new Map<string, FallbackMode>()
const appDefaultConfigs = new Map<string, AppSegmentConfig>()
......@@ -2642,6 +2658,17 @@ export default async function build(
)
if (pageType === 'app' && originalAppPath) {
if (
isAppCacheComponentsEnabled &&
!isAppRouteRoute(originalAppPath)
) {
// Include pages without exports: an omitted policy
// cannot silently inherit another route's closure.
paramMatchingByRoute.set(
originalAppPath,
workerResult.paramMatching
)
}
appNormalizedPaths.set(originalAppPath, page)
// TODO-APP: handle prerendering with edge
if (isEdgeRuntime(pageRuntime)) {
......@@ -2684,9 +2711,11 @@ export default async function build(
originalAppPath,
workerResult.prerenderedRoutes
)
ssgPageRoutes = workerResult.prerenderedRoutes.map(
(route) => route.pathname
ssgPageRoutes = workerResult.prerenderedRoutes
.filter(
(route) => route.isPrerenderOutput !== false
)
.map((route) => route.pathname)
isSSG = true
}
......@@ -2884,6 +2913,10 @@ export default async function build(
})
)
if (isAppCacheComponentsEnabled) {
validateParamMatchingCoherence(paramMatchingByRoute)
}
const errorPageResult = await errorPageStaticResult
const nonStaticErrorPage =
(await errorPageHasCustomGetInitialProps) ||
......@@ -3266,13 +3299,20 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error'
// Legacy dynamicParams=false closes the entire route tuple.
const notFoundParams =
// Explicit matching instead identifies the affected parameters.
const paramMatching = paramMatchingByRoute.get(originalAppPath)
let notFoundParams: readonly string[] | undefined
if (paramMatching) {
notFoundParams = Object.keys(paramMatching).filter(
(name) => paramMatching[name] === 'not-found'
)
} else if (
fallbackModes.get(originalAppPath) === FallbackMode.NOT_FOUND
? Object.keys(
) {
notFoundParams = Object.keys(
getRouteRegex(normalizeAppPath(originalAppPath)).groups
)
: undefined
}
const isRoutePPREnabled: boolean = appConfig
? isAppCacheComponentsEnabled
: false
......@@ -3377,13 +3417,16 @@ export default async function build(
prerenderCandidate: PrerenderedRoute | undefined,
hasEmptyStaticShell: boolean | undefined
) => {
// If the route has an empty static shell and is not configured to
// throw on empty static shell, then we should use the blocking
// static render mode.
// An unconfigured parameter uses its shell to infer the miss mode.
// This is separate from validation: even a required validation
// render can be empty when the user opts out with instant=false.
// Without matching configuration, preserve the existing heuristic
// for optional, more generic shells.
if (
prerenderCandidate &&
hasEmptyStaticShell &&
!prerenderCandidate.throwOnEmptyStaticShell &&
(matcher.isFallbackModeInferred ||
!prerenderCandidate.throwOnEmptyStaticShell) &&
matcher.fallbackMode === FallbackMode.PRERENDER
) {
return FallbackMode.BLOCKING_STATIC_RENDER
......@@ -3754,6 +3797,12 @@ export default async function build(
}
if (!hasRevalidateZero && isDynamicRoute(page)) {
const paramMatching = paramMatchingByRoute.get(originalAppPath)
const notFoundParams = paramMatching
? Object.keys(paramMatching).filter(
(name) => paramMatching[name] === 'not-found'
)
: undefined
// When PPR fallbacks aren't used, we need to include it here. If
// they are enabled, then it'll already be included in the
// prerendered routes.
......@@ -4006,12 +4055,19 @@ export default async function build(
}
prerenderManifest.dynamicRoutes[prerenderOutputPathname] = {
notFoundParams,
experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams:
route.remainingPrerenderableParams,
throwOnEmptyStaticShell:
prerenderCandidate?.throwOnEmptyStaticShell,
_isEnsureStaticPage: isEnsureStaticPage || undefined,
// Only PPR routes use static-shell validation. Without a
// build-time prerender, false lets runtime rendering resolve
// the remaining prerenderable params during the static phase.
throwOnEmptyStaticShell: isRoutePPREnabled
? prerenderCandidate
? prerenderCandidate.throwOnEmptyStaticShell
: false
: undefined,
renderingMode: isAppPPREnabled
? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC
......@@ -4026,6 +4082,16 @@ export default async function build(
),
dataRoute,
fallback,
isExplicitlyBlocking:
fallbackMode === FallbackMode.BLOCKING_STATIC_RENDER &&
route.fallbackRouteParams.some(
({ paramName }) =>
paramMatchingByRoute.get(originalAppPath)?.[
paramName
] === 'blocking'
)
? true
: undefined,
fallbackRevalidate: fallbackCacheControl?.revalidate,
fallbackExpire: fallbackCacheControl?.expire,
fallbackStatus: meta.status,
......@@ -4768,6 +4834,10 @@ export default async function build(
})
)
if (process.env.NEXT_PRIVATE_DEBUG_PARAM_MATCHING) {
printPrerenderMatchers(prerenderManifest, routesManifest.dynamicRoutes)
}
if (bundler === Bundler.Turbopack) {
await nextBuildSpan
.traceChild('write-route-bundle-stats')
......
......@@ -20,13 +20,65 @@ import {
import type { DynamicParamTypes } from '../../../shared/lib/app-router-types'
import { resolveEnsureStaticConfig } from '../../../server/app-render/segment-config/ensure-static'
import { anySegmentHasPartialPrefetchingEnabled } from '../../../server/app-render/instant-validation/instant-config'
import { isPlainObject } from '../../../shared/lib/is-plain-object'
type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]>
export const PARAM_MATCHING_MODES = [
'not-found',
'blocking',
'fallback',
'dynamic',
] as const
export type ParamMatchingMode = (typeof PARAM_MATCHING_MODES)[number]
export type ParamMatching = Record<string, ParamMatchingMode>
function validateParamMatchingExport(
route: string,
filePath: string | undefined,
exportName: string,
value: unknown,
visibleParamNames: readonly string[]
): ParamMatching {
if (!isPlainObject(value)) {
const valueType =
value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value
throw new Error(
`Invalid value from \`${exportName}\` for "${route}". Expected an object, but received ${valueType}.`
)
}
const paramMatching: ParamMatching = {}
for (const [paramName, mode] of Object.entries(
value as Record<string, unknown>
)) {
if (!visibleParamNames.includes(paramName)) {
throw new Error(
`Invalid parameter "${paramName}" in \`${exportName}\` for "${route}". The export in "${filePath}" may only configure parameters defined at or above its segment.`
)
}
if (!PARAM_MATCHING_MODES.includes(mode as ParamMatchingMode)) {
throw new Error(
`Invalid mode for parameter "${paramName}" in \`${exportName}\` for "${route}". Expected "not-found", "blocking", "fallback", or "dynamic", but received ${JSON.stringify(mode)}.`
)
}
paramMatching[paramName] = mode as ParamMatchingMode
}
return paramMatching
}
/**
* Parses the app config and attaches it to the segment.
*/
function attach(segment: AppSegment, userland: unknown, route: string) {
function attach(
segment: AppSegment,
userland: unknown,
route: string,
visibleParamNames: readonly string[]
) {
// If the userland is not an object, then we can't do anything with it.
if (typeof userland !== 'object' || userland === null) {
return
......@@ -63,6 +115,45 @@ function attach(segment: AppSegment, userland: unknown, route: string) {
)
}
}
const hasStaticParamMatching = 'unstable_paramMatching' in userland
const hasGeneratedParamMatching = 'unstable_generateParamMatching' in userland
if (hasStaticParamMatching || hasGeneratedParamMatching) {
if (hasStaticParamMatching && hasGeneratedParamMatching) {
throw new Error(
`Route "${route}" cannot export both \`unstable_paramMatching\` and \`unstable_generateParamMatching\`.`
)
}
if (hasStaticParamMatching) {
segment.paramMatching = validateParamMatchingExport(
route,
segment.filePath,
'unstable_paramMatching',
userland.unstable_paramMatching,
visibleParamNames
)
} else {
const generate = userland.unstable_generateParamMatching
if (typeof generate !== 'function') {
throw new Error(
`Route "${route}" must export \`unstable_generateParamMatching\` as a function.`
)
}
const { filePath } = segment
// Retain the module's scope without evaluating user code until static
// path generation has established its work store and cache context.
segment.paramMatching = async () =>
validateParamMatchingExport(
route,
filePath,
'unstable_generateParamMatching',
await generate(),
visibleParamNames
)
}
}
}
export type AppSegment = {
......@@ -71,10 +162,18 @@ export type AppSegment = {
paramType: DynamicParamTypes | undefined
filePath: string | undefined
config: AppSegmentConfig | undefined
paramMatching: ParamMatching | (() => Promise<ParamMatching>) | undefined
generateStaticParams: GenerateStaticParams | undefined
createEmptyParamsError?: () => Error
}
// Preserve parallel branches for parameter matching inheritance separately
// from the flat list used by generateStaticParams.
export type AppSegmentTree = [
segment: AppSegment,
parallelRoutes: AppSegmentTree[],
]
/**
* Walks the loader tree and collects the generate parameters for each segment.
*
......@@ -88,6 +187,7 @@ async function collectAppPageSegments(
// We keep track of unique segments, since with parallel routes, it's possible
// to see the same segment multiple times.
const segments: AppSegment[] = []
const segmentTree: AppSegmentTree[] = []
const rootLoaderTree = routeModule.userland.loaderTree
......@@ -105,10 +205,20 @@ async function collectAppPageSegments(
)
// Queue will store loader trees.
const queue: LoaderTree[] = [rootLoaderTree]
const queue: Array<{
loaderTree: LoaderTree
visibleParamNames: string[]
parentChildren: AppSegmentTree[]
}> = [
{
loaderTree: rootLoaderTree,
visibleParamNames: [],
parentChildren: segmentTree,
},
]
while (queue.length > 0) {
const loaderTree = queue.shift()!
const { loaderTree, visibleParamNames, parentChildren } = queue.shift()!
const [name, parallelRoutes] = loaderTree
// Process current node
......@@ -116,6 +226,9 @@ async function collectAppPageSegments(
const isClientComponent = userland && isClientReference(userland)
const param = getSegmentParam(name)
const currentVisibleParamNames = param
? [...visibleParamNames, param.paramName]
: visibleParamNames
const segment: AppSegment = {
name,
......@@ -123,12 +236,18 @@ async function collectAppPageSegments(
paramType: param?.paramType,
filePath,
config: undefined,
paramMatching: undefined,
generateStaticParams: undefined,
}
// Only server components can have app segment configurations
if (!isClientComponent) {
attach(segment, userland, routeModule.definition.pathname)
attach(
segment,
userland,
routeModule.definition.pathname,
currentVisibleParamNames
)
if (segment.config) {
segment.config.prefetch = prefetchConfig
......@@ -150,14 +269,20 @@ async function collectAppPageSegments(
) {
segments.push(segment)
}
const children: AppSegmentTree[] = []
parentChildren.push([segment, children])
// Add all parallel routes to the queue
for (const parallelRoute of Object.values(parallelRoutes)) {
queue.push(parallelRoute)
queue.push({
loaderTree: parallelRoute,
visibleParamNames: currentVisibleParamNames,
parentChildren: children,
})
}
}
return segments
return { segments, segmentTree }
}
/**
......@@ -166,9 +291,7 @@ async function collectAppPageSegments(
* @param routeModule the app route module
* @returns the segments for the app route module
*/
async function collectAppRouteSegments(
routeModule: AppRouteRouteModule
): Promise<AppSegment[]> {
async function collectAppRouteSegments(routeModule: AppRouteRouteModule) {
// The route file may be an async module (top-level await), so the userland
// module must be resolved before its exports can be inspected.
await routeModule.ensureUserland()
......@@ -189,6 +312,7 @@ async function collectAppRouteSegments(
paramType: param?.paramType,
filePath: undefined,
config: undefined,
paramMatching: undefined,
generateStaticParams: undefined,
} satisfies AppSegment
})
......@@ -200,9 +324,13 @@ async function collectAppRouteSegments(
segment.filePath = routeModule.definition.filename
// Extract the segment config from the userland module.
attach(segment, routeModule.userland, routeModule.definition.pathname)
attach(segment, routeModule.userland, routeModule.definition.pathname, [])
return segments
let segmentTree: AppSegmentTree[] = []
for (let index = segments.length - 1; index >= 0; index--) {
segmentTree = [[segments[index], segmentTree]]
}
return { segments, segmentTree }
}
/**
......@@ -214,7 +342,7 @@ async function collectAppRouteSegments(
export function collectSegments(
routeModule: AppRouteRouteModule | AppPageRouteModule,
config: { cacheComponents: boolean; partialPrefetching: boolean } | undefined
): Promise<AppSegment[]> | AppSegment[] {
) {
if (isAppRouteRouteModule(routeModule)) {
return collectAppRouteSegments(routeModule)
}
......
......@@ -7,30 +7,151 @@ import {
filterUniqueParams,
generateRouteStaticParams,
} from './app'
import { resolveParamMatching } from './param-matching'
import type { PrerenderedRoute } from './types'
import type { WorkStore } from '../../server/app-render/work-async-storage.external'
import type { AppSegment } from '../segment-config/app/app-segments'
function pathnameSegments(
...segments: Array<string | [string, boolean]>
): Array<{
paramName: string
hasGenerateStaticParams: boolean
}> {
return segments.map((segment) =>
Array.isArray(segment)
? {
paramName: segment[0],
hasGenerateStaticParams: segment[1],
}
: {
paramName: segment,
hasGenerateStaticParams: false,
}
)
...paramNames: string[]
): Array<{ paramName: string }> {
return paramNames.map((paramName) => ({ paramName }))
}
describe('assignStaticShellMetadata', () => {
it('keeps the most-specific shell without an explicit fallback', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: { lang: 'en', top: 't1' },
pathname: '/en/t1/[bottom]',
encodedPathname: '/en/t1/[bottom]',
fallbackRouteParams: [{ paramName: 'bottom', paramType: 'dynamic' }],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: false,
},
{
params: { lang: 'en', top: 't1', bottom: 'b1' },
pathname: '/en/t1/b1',
encodedPathname: '/en/t1/b1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('lang', 'top', 'bottom')
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
})
it('requires an explicit fallback shell to be non-empty', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: { lang: 'en', top: 't1' },
pathname: '/en/t1/[bottom]',
encodedPathname: '/en/t1/[bottom]',
fallbackRouteParams: [{ paramName: 'bottom', paramType: 'dynamic' }],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: false,
},
{
params: { lang: 'en', top: 't1', bottom: 'b1' },
pathname: '/en/t1/b1',
encodedPathname: '/en/t1/b1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('lang', 'top', 'bottom'),
'bottom'
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
})
it('validates a generic blocking shell when no example reaches an explicit fallback', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[top]/items/[bottom]',
encodedPathname: '/[top]/items/[bottom]',
fallbackRouteParams: [
{ paramName: 'top', paramType: 'dynamic' },
{ paramName: 'bottom', paramType: 'dynamic' },
],
fallbackMode: FallbackMode.BLOCKING_STATIC_RENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: false,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('top', 'bottom'),
'bottom'
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
})
it('prefers a reachable explicit fallback over a generic blocking shell', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[top]/items/[bottom]',
encodedPathname: '/[top]/items/[bottom]',
fallbackRouteParams: [
{ paramName: 'top', paramType: 'dynamic' },
{ paramName: 'bottom', paramType: 'dynamic' },
],
fallbackMode: FallbackMode.BLOCKING_STATIC_RENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { top: 't1' },
pathname: '/t1/items/[bottom]',
encodedPathname: '/t1/items/[bottom]',
fallbackRouteParams: [{ paramName: 'bottom', paramType: 'dynamic' }],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: false,
},
{
params: { top: 't1', bottom: 'b1' },
pathname: '/t1/items/b1',
encodedPathname: '/t1/items/b1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.PRERENDER,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('top', 'bottom'),
'bottom'
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(false)
})
it('should assign throwOnEmptyStaticShell true for a static route with no children', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
......@@ -206,25 +327,12 @@ describe('assignStaticShellMetadata', () => {
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('id', ['name', true], 'extra')
pathnameSegments('id', 'name', 'extra')
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[2].remainingPrerenderableParams).toBeUndefined()
})
it('should handle empty input', () => {
......@@ -447,113 +555,65 @@ describe('assignStaticShellMetadata', () => {
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
})
})
it('should specialize only unresolved params backed by generateStaticParams', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]',
encodedPathname: '/[one]/[two]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { one: 'b' },
pathname: '/b/[two]',
encodedPathname: '/b/[two]',
fallbackRouteParams: [
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two')
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
describe('resolveParamMatching', () => {
it('starts a descendant generator while its ancestor is still pending', async () => {
let releaseParent!: () => void
const parentGate = new Promise<void>((resolve) => {
releaseParent = resolve
})
let notifyChildStarted!: () => void
const childStarted = new Promise<void>((resolve) => {
notifyChildStarted = resolve
})
it('should stop specializing once it reaches a purely dynamic param', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]/[three]',
encodedPathname: '/[one]/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
const resolvedParamMatching = resolveParamMatching(
'/[lang]/[top]',
[
[
{
paramName: 'three',
name: '[lang]',
paramName: 'lang',
paramType: 'dynamic',
filePath: 'app/[lang]/layout.tsx',
config: undefined,
generateStaticParams: undefined,
paramMatching: async () => {
await parentGate
return { lang: 'not-found' }
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
[
[
{
params: { one: 'a' },
pathname: '/a/[two]/[three]',
encodedPathname: '/a/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'two',
name: '[top]',
paramName: 'top',
paramType: 'dynamic',
filePath: 'app/[lang]/[top]/layout.tsx',
config: undefined,
generateStaticParams: undefined,
paramMatching: async () => {
notifyChildStarted()
return { top: 'blocking' }
},
{
paramName: 'three',
paramType: 'dynamic',
},
[],
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two', ['three', true])
],
],
],
pathnameSegments('lang', 'top')
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
// The child must not wait for the parent, but it need not start in the
// same synchronous turn as resolveParamMatching.
await childStarted
releaseParent()
await expect(resolvedParamMatching).resolves.toEqual({
lang: 'not-found',
top: 'blocking',
})
})
})
......
import type { Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { AppSegment } from '../segment-config/app/app-segments'
import type {
AppSegment,
AppSegmentTree,
} from '../segment-config/app/app-segments'
import type {
FallbackRouteParam,
PrerenderRouteMatcher,
......@@ -43,6 +46,11 @@ import {
throwIncompleteStaticParamsErrorInStaticRoute,
throwMissingGspErrorInStaticRoute,
} from '../../shared/lib/errors/ensure-static-gsp-errors'
import {
resolveParamMatching,
getParamMatchingFallbackMode,
validateParamMatchingParams,
} from './param-matching'
/**
* Filters out duplicate parameters from a list of parameters.
......@@ -418,28 +426,65 @@ interface TrieNode {
* These are the routes whose concrete parameters lead to this node in the Trie.
*/
routes: PrerenderedRoute[]
/**
* Whether an ancestor selected the shell that validates an explicit policy boundary.
* This is assigned before the node is visited during the Trie traversal.
*/
hasValidatedPolicyAncestor: boolean
}
function getRemainingPrerenderableParams(
params: Params,
fallbackRouteParams: readonly FallbackRouteParam[],
pathnameSegments: ReadonlyArray<{
readonly paramName: string
readonly isPrerenderable: boolean
}>
): readonly FallbackRouteParam[] | undefined {
const fallbackRouteParamsByName = new Map(
fallbackRouteParams.map((param) => [param.paramName, param])
)
const remainingPrerenderableParams: FallbackRouteParam[] = []
// Only unresolved pathname params that can still be prerendered belong
// here. Once we hit a purely dynamic param, the rest of the shell also
// stays dynamic and cannot be completed into a more specific prerender.
for (const segment of pathnameSegments) {
if (params.hasOwnProperty(segment.paramName)) continue
if (!segment.isPrerenderable) break
const fallbackRouteParam = fallbackRouteParamsByName.get(segment.paramName)
if (!fallbackRouteParam) break
remainingPrerenderableParams.push(fallbackRouteParam)
}
return remainingPrerenderableParams.length > 0
? remainingPrerenderableParams
: undefined
}
/**
* Assigns static shell metadata to each prerendered route.
* This function uses a Trie data structure to efficiently determine whether each route
* should throw an error when its static shell is empty and whether a fallback shell
* can still be completed into a more specific prerendered shell.
* should throw an error when its static shell is empty.
*
* A route should not throw on empty static shell if it has child routes in the Trie. For example,
* if we have two routes, `/blog/first-post` and `/blog/[slug]`, the route for
* `/blog/[slug]` should not throw because `/blog/first-post` is a more specific concrete route.
*
* @param prerenderedRoutes - The prerendered routes.
* @param pathnameSegments - The pathname params and whether each one is still
* prerenderable via generateStaticParams.
* @param pathnameSegments - The pathname params in route order.
* @param explicitFallbackParamName - The first parameter explicitly configured
* as fallback, when one exists.
*/
export function assignStaticShellMetadata(
prerenderedRoutes: readonly PrerenderedRoute[],
pathnameSegments: ReadonlyArray<{
readonly paramName: string
readonly hasGenerateStaticParams: boolean
}>
}>,
explicitFallbackParamName?: string
): void {
// If there are no routes to process, exit early.
if (prerenderedRoutes.length === 0) {
......@@ -448,7 +493,11 @@ export function assignStaticShellMetadata(
// Initialize the root of the Trie. This node represents the starting point
// before any parameters have been considered.
const root: TrieNode = { children: new Map(), routes: [] }
const root: TrieNode = {
children: new Map(),
routes: [],
hasValidatedPolicyAncestor: false,
}
// Phase 1: Build the Trie.
// Iterate over each prerendered route and insert it into the Trie.
......@@ -491,6 +540,7 @@ export function assignStaticShellMetadata(
childNode = {
children: new Map(),
routes: [],
hasValidatedPolicyAncestor: false,
}
currentNode.children.set(valueKey, childNode)
}
......@@ -508,19 +558,38 @@ export function assignStaticShellMetadata(
// This is done using an iterative Depth-First Search (DFS) approach with an
// explicit stack to avoid JavaScript's recursion depth limits (stack overflow)
// for very deep routing structures.
const stack: TrieNode[] = [root] // Initialize the stack with the root node.
const stack: TrieNode[] = [root]
while (stack.length > 0) {
const node = stack.pop()! // Pop the next node to process from the stack.
const node = stack.pop()!
const { hasValidatedPolicyAncestor } = node
// `hasChildren` indicates if this node has any more specific concrete
// parameter combinations branching off from it. If true, it means this
// node represents a prefix for other, more specific routes.
const hasChildren = node.children.size > 0
let policyValidationRoute: PrerenderedRoute | undefined
// If the current node has routes associated with it (meaning, routes whose
// concrete parameters lead to this node's path in the Trie).
if (node.routes.length > 0) {
if (!hasValidatedPolicyAncestor && explicitFallbackParamName) {
for (const route of node.routes) {
const fallbackRouteParams = route.fallbackRouteParams ?? []
const isExplicitFallback =
route.fallbackMode === FallbackMode.PRERENDER &&
fallbackRouteParams[0]?.paramName === explicitFallbackParamName
if (
isExplicitFallback &&
(!policyValidationRoute ||
fallbackRouteParams.length >
(policyValidationRoute.fallbackRouteParams?.length ?? 0))
) {
policyValidationRoute = route
}
}
}
// Determine the minimum number of fallback parameters among all routes
// that are associated with this current Trie node. This is used to
// identify if a route should not throw on empty static shell relative to another route *at the same level*
......@@ -537,9 +606,12 @@ export function assignStaticShellMetadata(
// Now, for each `PrerenderedRoute` associated with this node:
for (const route of node.routes) {
// A route is ok not to throw on an empty static shell (and thus
// `throwOnEmptyStaticShell` should be `false`) if either of the
// following conditions is met:
// An explicit fallback or blocking boundary must validate exactly one
// shell for this branch. Once that succeeds, more specific shells do
// not need to repeat the same validation.
//
// Without an explicit policy validation, a route is ok not to throw
// on an empty static shell if either of the following conditions is met:
// 1. `hasChildren` is true: This node has further concrete parameter children.
// This means the current route is a parent to more specific routes (e.g.,
// `/blog/[slug]` should not throw when concrete routes like `/blog/first-post` exist).
......@@ -549,7 +621,10 @@ export function assignStaticShellMetadata(
// This implies the current route is a more general version that should not throw
// compared to a more specific route that has fewer fallback parameters
// (e.g., `/1234/[...slug]` should not throw relative to `/[id]/[...slug]`).
if (
if (policyValidationRoute) {
route.throwOnEmptyStaticShell = route === policyValidationRoute
} else if (
hasValidatedPolicyAncestor ||
hasChildren ||
(route.fallbackRouteParams &&
route.fallbackRouteParams.length > minFallbacks)
......@@ -558,47 +633,14 @@ export function assignStaticShellMetadata(
} else {
route.throwOnEmptyStaticShell = true // Should throw on empty static shell.
}
if (route.fallbackRouteParams && route.fallbackRouteParams.length > 0) {
const fallbackRouteParamsByName = new Map(
route.fallbackRouteParams.map((param) => [param.paramName, param])
)
const remainingPrerenderableParams: FallbackRouteParam[] = []
// Only unresolved pathname params that can still be filled by
// generateStaticParams belong here. Once we hit an unresolved param
// that is purely dynamic, the rest of the shell also stays dynamic
// and cannot be completed into a more specific prerendered shell.
for (const segment of pathnameSegments) {
if (route.params.hasOwnProperty(segment.paramName)) {
continue
}
if (!segment.hasGenerateStaticParams) {
break
}
const fallbackRouteParam = fallbackRouteParamsByName.get(
segment.paramName
)
if (!fallbackRouteParam) {
break
}
remainingPrerenderableParams.push(fallbackRouteParam)
}
route.remainingPrerenderableParams =
remainingPrerenderableParams.length > 0
? remainingPrerenderableParams
: undefined
}
}
}
// Add all children of the current node to the stack. This ensures that
// the traversal continues to explore deeper paths in the Trie.
for (const child of node.children.values()) {
child.hasValidatedPolicyAncestor =
hasValidatedPolicyAncestor || policyValidationRoute !== undefined
stack.push(child)
}
}
......@@ -831,6 +873,7 @@ export async function buildAppStaticPaths({
durableUseCacheEntries,
staticPageGenerationTimeout,
segments,
segmentTree,
isrFlushToDisk,
cacheHandler,
cacheLifeProfiles,
......@@ -855,6 +898,7 @@ export async function buildAppStaticPaths({
durableUseCacheEntries: boolean
staticPageGenerationTimeout: number
segments: readonly Readonly<AppSegment>[]
segmentTree: readonly AppSegmentTree[]
distDir: string
isrFlushToDisk?: boolean
fetchCacheKeyPrefix?: string
......@@ -903,6 +947,15 @@ export async function buildAppStaticPaths({
route
)
const hasParamMatchingExport = segments.some(
(segment) => segment.paramMatching !== undefined
)
if (hasParamMatchingExport && !cacheComponents) {
throw new Error(
`Route "${page}" cannot use parameter matching without enabling \`cacheComponents\`.`
)
}
const afterRunner = new AfterRunner()
const store = createWorkStore({
......@@ -930,6 +983,39 @@ export async function buildAppStaticPaths({
previouslyRevalidatedTags: [],
})
const paramMatching = hasParamMatchingExport
? await workAsyncStorage.run(store, async () => {
const generatorStore: BuildTimeGeneratorStore = {
type: 'build-time-generator',
functionName: 'unstable_generateParamMatching',
phase: 'render',
implicitTags: await getImplicitTags(page, page, null),
// Matching configuration does not receive concrete parameter values.
rootParams: {},
}
return workUnitAsyncStorage.run(
generatorStore,
resolveParamMatching,
page,
segmentTree,
pathnameRouteParamSegments
)
})
: undefined
// Validate the effective route policy, after layout overrides and parallel
// branches have been merged. Navigation mode cannot serve a fallback and
// resume it, or leave any parameter permanently dynamic.
if (isEnsureStaticPage && paramMatching) {
for (const [paramName, mode] of Object.entries(paramMatching)) {
if (mode === 'fallback' || mode === 'dynamic') {
throw new Error(
`Route "${page}" cannot configure parameter "${paramName}" as "${mode}" with \`unstable_ensureStatic = "navigation"\`. Use "blocking" or "not-found" parameter matching, or remove the navigation constraint.`
)
}
}
}
const routeParams = await workAsyncStorage.run(
store,
generateRouteStaticParams,
......@@ -940,17 +1026,62 @@ export async function buildAppStaticPaths({
nextConfigOutput === 'export'
)
const generatedParamNames = new Set<string>()
const missingParamNames = new Set<string>()
if (routeParams.length > 0) {
for (const { paramName } of pathnameRouteParamSegments) {
for (const params of routeParams) {
for (const paramName of Object.keys(params)) {
if (paramName in params) {
generatedParamNames.add(paramName)
} else {
missingParamNames.add(paramName)
}
}
}
}
// An explicitly prerenderable parameter also makes its unconfigured prefix
// prerenderable, even without build-time examples. Only the unconfigured
// suffix after this boundary can remain permanently dynamic.
const lastConfiguredPrerenderableParamIndex =
pathnameRouteParamSegments.findLastIndex(({ paramName }) => {
const mode = paramMatching?.[paramName]
return mode === 'blocking' || mode === 'fallback'
})
const prerenderablePathSegments = pathnameRouteParamSegments.map(
(segment) => ({
(segment, index) => {
const mode = paramMatching?.[segment.paramName]
return {
paramName: segment.paramName,
hasGenerateStaticParams: generatedParamNames.has(segment.paramName),
})
isPrerenderable:
mode === 'blocking' ||
mode === 'fallback' ||
(mode === undefined &&
(index < lastConfiguredPrerenderableParamIndex ||
generatedParamNames.has(segment.paramName))),
}
}
)
let explicitFallbackRouteParams: readonly FallbackRouteParam[] | undefined
if (paramMatching) {
const firstFallbackParamIndex = pathnameRouteParamSegments.findIndex(
({ paramName }) => paramMatching[paramName] === 'fallback'
)
if (firstFallbackParamIndex !== -1) {
explicitFallbackRouteParams = pathnameRouteParamSegments
.slice(firstFallbackParamIndex)
.map(({ paramName, paramType }) => ({ paramName, paramType }))
}
}
if (paramMatching) {
validateParamMatchingParams(
page,
paramMatching,
generatedParamNames,
missingParamNames,
pathnameRouteParamSegments,
nextConfigOutput
)
}
await afterRunner.executeAfter()
......@@ -987,19 +1118,10 @@ export async function buildAppStaticPaths({
}
}
const missingParamNames: string[] = []
for (const { paramName } of pathnameRouteParamSegments) {
if (
routeParams.length === 0 ||
routeParams.some((params) => !(paramName in params))
) {
missingParamNames.push(paramName)
}
}
// Determine if all the segments have had their parameters provided.
const hadAllParamsGenerated =
pathnameRouteParamSegments.length === 0 || missingParamNames.length === 0
pathnameRouteParamSegments.length === 0 ||
(routeParams.length > 0 && missingParamNames.size === 0)
if (
nextConfigOutput === 'export' &&
......@@ -1007,7 +1129,7 @@ export async function buildAppStaticPaths({
!hadAllParamsGenerated
) {
throw new Error(
`Page "${page}" returned incomplete params from "generateStaticParams()". With "output: export", every params object must include all dynamic route parameters. Missing: ${missingParamNames.map((name) => `"${name}"`).join(', ')}. See more info here: https://nextjs.org/docs/messages/generate-static-params`
`Page "${page}" returned incomplete params from "generateStaticParams()". With "output: export", every params object must include all dynamic route parameters. Missing: ${[...missingParamNames].map((name) => `"${name}"`).join(', ')}. See more info here: https://nextjs.org/docs/messages/generate-static-params`
)
}
......@@ -1019,7 +1141,9 @@ export async function buildAppStaticPaths({
// so empty `routeParams` implies that no `generateStaticParams` is present at all
throwMissingGspErrorInStaticRoute(page)
} else if (!hadAllParamsGenerated) {
throwIncompleteStaticParamsErrorInStaticRoute(page, missingParamNames)
throwIncompleteStaticParamsErrorInStaticRoute(page, [
...missingParamNames,
])
}
}
......@@ -1033,7 +1157,7 @@ export async function buildAppStaticPaths({
const supportsRoutePreGeneration =
hadAllParamsGenerated || !process.env.__NEXT_DEV_SERVER
const fallbackMode = dynamicParams
const inferredFallbackMode = dynamicParams
? supportsRoutePreGeneration
? isRoutePPREnabled
? isEnsureStaticPage
......@@ -1044,10 +1168,128 @@ export async function buildAppStaticPaths({
: undefined
: FallbackMode.NOT_FOUND
const rootParamSet = new Set(rootParamKeys)
const fallbackMode = paramMatching
? getParamMatchingFallbackMode(
paramMatching,
pathnameRouteParamSegments,
inferredFallbackMode,
rootParamSet
)
: inferredFallbackMode
const getRouteFallbackMode = (
fallbackRouteParams: readonly FallbackRouteParam[],
fallbackRootParams: readonly string[]
): FallbackMode | undefined => {
if (paramMatching) {
return getParamMatchingFallbackMode(
paramMatching,
fallbackRouteParams,
inferredFallbackMode,
rootParamSet
)
}
return calculateFallbackMode(
dynamicParams,
fallbackRootParams,
fallbackMode
)
}
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>()
const blockingCandidatesByPathname = new Map<string, PrerenderedRoute>()
const prerenderRouteMatchersByPathname = new Map<
string,
PrerenderRouteMatcher
>()
// Convert rootParamKeys to Set for O(1) lookup.
const rootParamSet = new Set(rootParamKeys)
const addPrerenderCandidate = (
params: Params,
pathname: string,
encodedPathname: string,
fallbackRouteParams: readonly FallbackRouteParam[],
fallbackRootParams: readonly string[]
): void => {
const routeFallbackMode = getRouteFallbackMode(
fallbackRouteParams,
fallbackRootParams
)
const remainingPrerenderableParams =
cacheComponents && fallbackRouteParams.length > 0
? getRemainingPrerenderableParams(
params,
fallbackRouteParams,
prerenderablePathSegments
)
: undefined
if (
fallbackRouteParams.length > 0 &&
(isRoutePPREnabled || paramMatching)
) {
prerenderRouteMatchersByPathname.set(pathname, {
pathname,
fallbackRouteParams,
fallbackMode: routeFallbackMode,
isFallbackModeInferred:
paramMatching &&
routeFallbackMode === FallbackMode.PRERENDER &&
paramMatching[fallbackRouteParams[0].paramName] === undefined &&
remainingPrerenderableParams?.[0]?.paramName ===
fallbackRouteParams[0].paramName
? true
: undefined,
fallbackRootParams,
remainingPrerenderableParams,
})
}
const prerenderCandidate: PrerenderedRoute = {
params,
pathname,
encodedPathname,
fallbackRouteParams,
fallbackMode: routeFallbackMode,
fallbackRootParams,
remainingPrerenderableParams,
isPrerenderOutput:
paramMatching &&
fallbackRouteParams.length > 0 &&
routeFallbackMode === FallbackMode.BLOCKING_STATIC_RENDER
? false
: undefined,
throwOnEmptyStaticShell: true,
}
if (isEnsureStaticPage && fallbackRouteParams.length > 0) {
// Navigation mode still needs the generic render's prefetch data. Other
// prefixes only need matchers: /en/[slug] can admit a novel slug beneath
// a closed language without rendering or serving a partial fallback.
if (pathname === page) {
prerenderedRoutesByPathname.set(pathname, prerenderCandidate)
}
return
}
// Explicit blocking policies do not produce fallback outputs, but may
// still need a render for prefetch hints and shell validation. Keep their
// candidates until we know whether a more specific render covers them.
// Not-found candidates do not need to render at all.
if (
paramMatching &&
fallbackRouteParams.length > 0 &&
routeFallbackMode !== FallbackMode.PRERENDER
) {
if (routeFallbackMode === FallbackMode.BLOCKING_STATIC_RENDER) {
blockingCandidatesByPathname.set(pathname, prerenderCandidate)
}
return
}
prerenderedRoutesByPathname.set(pathname, prerenderCandidate)
}
if (hadAllParamsGenerated || isRoutePPREnabled) {
let paramsToProcess = routeParams
......@@ -1077,19 +1319,7 @@ export async function buildAppStaticPaths({
// Add the base route, this is the route with all the placeholders as it's
// derived from the `page` string.
prerenderedRoutesByPathname.set(page, {
params: {},
pathname: page,
encodedPathname: page,
fallbackRouteParams,
fallbackMode: calculateFallbackMode(
dynamicParams,
rootParamKeys,
fallbackMode
),
fallbackRootParams: rootParamKeys,
throwOnEmptyStaticShell: true,
})
addPrerenderCandidate({}, page, page, fallbackRouteParams, rootParamKeys)
}
filterUniqueParams(
......@@ -1113,10 +1343,9 @@ export async function buildAppStaticPaths({
if (!paramValue) {
if (
isRoutePPREnabled &&
// `ensureStatic = "navigation"` does not currently use fallbacks
// with some of the params filled in. We only use create route with all
// the params set to fallback so that ISR is set up correctly.
!isEnsureStaticPage
// Navigation mode does not render intermediate fallbacks, but
// parameter matching may still need their specialized matchers.
(!isEnsureStaticPage || paramMatching !== undefined)
) {
// Mark remaining params as fallback params.
fallbackRouteParams.push({ paramName, paramType })
......@@ -1183,48 +1412,50 @@ export async function buildAppStaticPaths({
pathname = normalizePathname(pathname)
prerenderedRoutesByPathname.set(pathname, {
addPrerenderCandidate(
params,
pathname,
encodedPathname: normalizePathname(encodedPathname),
normalizePathname(encodedPathname),
fallbackRouteParams,
fallbackMode: calculateFallbackMode(
dynamicParams,
fallbackRootParams,
fallbackMode
),
fallbackRootParams,
throwOnEmptyStaticShell: true,
})
fallbackRootParams
)
})
}
const prerenderedRoutes =
let prerenderedRoutes =
prerenderedRoutesByPathname.size > 0 ||
blockingCandidatesByPathname.size > 0 ||
lastDynamicSegmentHadGenerateStaticParams
? [...prerenderedRoutesByPathname.values()]
? [
...prerenderedRoutesByPathname.values(),
...blockingCandidatesByPathname.values(),
]
: undefined
// Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (prerenderedRoutes && cacheComponents) {
assignStaticShellMetadata(prerenderedRoutes, prerenderablePathSegments)
}
if (cacheComponents) {
const explicitFallbackParamName =
explicitFallbackRouteParams?.[0]?.paramName
const prerenderRouteMatchersByPathname = new Map<
string,
PrerenderRouteMatcher
>()
if (prerenderedRoutes && isRoutePPREnabled) {
for (const prerenderCandidate of prerenderedRoutes) {
if (!prerenderCandidate.fallbackRouteParams?.length) continue
prerenderRouteMatchersByPathname.set(prerenderCandidate.pathname, {
pathname: prerenderCandidate.pathname,
fallbackRouteParams: prerenderCandidate.fallbackRouteParams,
fallbackMode: prerenderCandidate.fallbackMode,
fallbackRootParams: prerenderCandidate.fallbackRootParams,
remainingPrerenderableParams:
prerenderCandidate.remainingPrerenderableParams,
})
if (prerenderedRoutes) {
assignStaticShellMetadata(
prerenderedRoutes,
prerenderablePathSegments,
explicitFallbackParamName
)
// Keep blocking candidates without a more specific render so the build
// can collect best-effort prefetch hints, even with instant=false. The
// renderer handles that validation opt-out; it must not skip this render.
// Explicit matching can skip candidates covered by a descendant.
// Without matching configuration, preserve every historical render:
// its output may still contribute the route's prefetch hints.
if (paramMatching !== undefined && !isEnsureStaticPage) {
prerenderedRoutes = prerenderedRoutes.filter(
(candidate) =>
candidate.fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER ||
candidate.throwOnEmptyStaticShell
)
}
}
}
......@@ -1233,5 +1464,11 @@ export async function buildAppStaticPaths({
? [...prerenderRouteMatchersByPathname.values()]
: undefined
return { fallbackMode, prerenderedRoutes, prerenderRouteMatchers }
return {
fallbackMode,
prerenderedRoutes,
prerenderRouteMatchers,
paramMatching,
explicitFallbackRouteParams,
}
}
......@@ -94,11 +94,14 @@ export function extractPathnameRouteParamSegmentsFromLoaderTree(
}>
params: Params
} {
const pathnameRouteParamSegments: Array<{
const segmentsByDepth = new Map<
number,
{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> = []
}
>()
const params: Params = {}
// BFS traversal with depth and path tracking
......@@ -153,7 +156,7 @@ export function extractPathnameRouteParamSegmentsFromLoaderTree(
// the target pathname. This prevents false matches like extracting
// [slug] from "/news/[slug]" when the tree has "/blog/[slug]"
if (validatePrefixMatch(currentPath, route)) {
pathnameRouteParamSegments.push({
segmentsByDepth.set(depth, {
name: segment,
paramName,
paramType,
......@@ -188,5 +191,12 @@ export function extractPathnameRouteParamSegmentsFromLoaderTree(
}
}
// Parallel slots can repeat a parameter, and route groups can make loader
// tree traversal encounter deeper URL parameters before shallower ones.
// Consumers need each parameter once, in URL order, not tree traversal order.
const pathnameRouteParamSegments = [...segmentsByDepth]
.sort(([a], [b]) => a - b)
.map(([, segment]) => segment)
return { pathnameRouteParamSegments, params }
}
import {
PARAM_MATCHING_MODES,
type AppSegment,
type AppSegmentTree,
type ParamMatching,
type ParamMatchingMode,
} from '../segment-config/app/app-segments'
import type { FallbackRouteParam } from './types'
import { FallbackMode } from '../../lib/fallback'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param'
type PolicyCandidate = {
readonly mode: ParamMatchingMode
readonly filePath: string | undefined
}
export async function resolveParamMatching(
page: string,
segmentTree: readonly AppSegmentTree[],
pathnameSegments: ReadonlyArray<{ readonly paramName: string }>
): Promise<ParamMatching | undefined> {
const configuredSegments: AppSegment[] = []
const nodes = [...segmentTree]
for (let index = 0; index < nodes.length; index++) {
const [segment, children] = nodes[index]
if (segment.paramMatching !== undefined) configuredSegments.push(segment)
nodes.push(...children)
}
if (configuredSegments.length === 0) return undefined
const routeParamNames = new Set(
pathnameSegments.map(({ paramName }) => paramName)
)
const candidates = new Map<string, PolicyCandidate[]>()
const paramsMissingPolicy = new Set<string>()
// Start independent generators together, before merging their results down
// each branch.
const fragments = new Map<AppSegment, ParamMatching>()
await Promise.all(
configuredSegments.map(async (segment) => {
const paramMatchingExport = segment.paramMatching!
const value =
typeof paramMatchingExport === 'function'
? await paramMatchingExport()
: paramMatchingExport
for (const paramName of Object.keys(value)) {
if (!routeParamNames.has(paramName)) {
const exportName =
typeof paramMatchingExport === 'function'
? 'unstable_generateParamMatching'
: 'unstable_paramMatching'
throw new Error(
`Invalid parameter "${paramName}" in \`${exportName}\` for "${page}". Parameter matching may only configure dynamic parameters in this route.`
)
}
}
fragments.set(segment, value)
})
)
function visit(
[segment, children]: AppSegmentTree,
inherited: ReadonlyMap<string, PolicyCandidate>,
paramNames: readonly string[]
) {
const branchCandidates = new Map(inherited)
const fragment = fragments.get(segment)
if (fragment) {
for (const [paramName, mode] of Object.entries(fragment)) {
branchCandidates.set(paramName, { mode, filePath: segment.filePath })
}
}
if (segment.paramName) paramNames = [...paramNames, segment.paramName]
if (children.length > 0) {
for (const child of children) visit(child, branchCandidates, paramNames)
return
}
// Compare the effective policies at every leaf, including leaves without
// exports. A sibling's override must not erase this branch's inheritance.
for (const paramName of paramNames) {
if (!branchCandidates.has(paramName)) {
paramsMissingPolicy.add(paramName)
}
}
for (const [paramName, candidate] of branchCandidates) {
const parallelCandidates = candidates.get(paramName)
if (!parallelCandidates) {
candidates.set(paramName, [candidate])
} else if (
!parallelCandidates.some(({ mode }) => mode === candidate.mode)
) {
parallelCandidates.push(candidate)
}
}
}
for (const root of segmentTree) visit(root, new Map(), [])
const policy: ParamMatching = {}
for (const { paramName } of pathnameSegments) {
const paramCandidates = candidates.get(paramName)
if (!paramCandidates) continue
const mode = paramCandidates[0].mode
if (paramCandidates.some((candidate) => candidate.mode !== mode)) {
const definitions = paramCandidates
.map(
(candidate) =>
`${candidate.filePath ?? '<unknown module>'} (${candidate.mode})`
)
.join(', ')
throw new Error(
`Route "${page}" has conflicting parallel parameter matching modes for parameter "${paramName}": ${definitions}.`
)
}
if (mode === 'not-found' && paramsMissingPolicy.has(paramName)) {
throw new Error(
`Parameter "${paramName}" in route "${page}" uses "not-found" in one parallel branch, but another branch has no explicit policy. Every parallel branch sharing this parameter must explicitly configure "not-found", either directly or through an inherited layout.`
)
}
policy[paramName] = mode
}
let previousPhase = -1
let previousParamName: string | undefined
let unconfiguredPrefixParamName: string | undefined
for (const { paramName } of pathnameSegments) {
const mode = policy[paramName]
if (!mode) {
unconfiguredPrefixParamName ??= paramName
continue
}
if (mode === 'not-found' && unconfiguredPrefixParamName !== undefined) {
throw new Error(
`Invalid parameter matching for "${page}": Parameter "${unconfiguredPrefixParamName}" must explicitly configure "not-found" before parameter "${paramName}" uses "not-found". Configure the preceding parameter directly or in an inherited layout; it cannot be closed by inference.`
)
}
const currentPhase = PARAM_MATCHING_MODES.indexOf(mode)
if (currentPhase < previousPhase) {
throw new Error(
`Invalid parameter matching for "${page}": parameter "${paramName}" uses "${mode}" after parameter "${previousParamName}" uses a later matching phase. Expected parameters in this order: "not-found", "blocking", "fallback", then "dynamic".`
)
}
previousPhase = currentPhase
previousParamName = paramName
}
return policy
}
/**
* Validate closure after every page's policies have been evaluated and merged.
* Identify each parameter definition by its normalized URL prefix, including
* the parameter name. /blog/[slug] and /shop/[slug] are independent; route
* groups and parallel slots are removed by normalization and share the same
* definition when their URL prefixes match.
*/
export function validateParamMatchingCoherence(
paramMatchingByRoute: ReadonlyMap<string, ParamMatching | undefined>
): void {
const parameters = new Map<string, [route: string, notFound: boolean]>()
for (const [appPath, paramMatching] of [...paramMatchingByRoute].sort(
([a], [b]) => a.localeCompare(b)
)) {
const route = normalizeAppPath(appPath)
let prefix = ''
for (const segment of route.split('/')) {
if (!segment) continue
prefix += `/${segment}`
const param = getSegmentParam(segment)
if (!param) continue
const notFound = paramMatching?.[param.paramName] === 'not-found'
const previous = parameters.get(prefix)
if (previous === undefined) {
parameters.set(prefix, [route, notFound])
} else if (previous[1] !== notFound) {
const closedRoute = notFound ? route : previous[0]
const openRoute = notFound ? previous[0] : route
throw new Error(
`Parameter "${param.paramName}" at "${prefix}" uses "not-found" in route "${closedRoute}". Route "${openRoute}" must explicitly configure "not-found" for this parameter, either directly or through an inherited layout.`
)
}
}
}
}
export function getParamMatchingFallbackMode(
paramMatching: Readonly<ParamMatching>,
fallbackRouteParams: readonly Pick<FallbackRouteParam, 'paramName'>[],
inferredFallbackMode: FallbackMode | undefined,
rootParamKeys: ReadonlySet<string>
): FallbackMode | undefined {
let hasInferredBlockingRoot = false
for (const { paramName } of fallbackRouteParams) {
switch (paramMatching[paramName]) {
case undefined:
if (rootParamKeys.has(paramName)) hasInferredBlockingRoot = true
break
case 'not-found':
return FallbackMode.NOT_FOUND
case 'blocking':
return FallbackMode.BLOCKING_STATIC_RENDER
case 'fallback':
case 'dynamic':
return hasInferredBlockingRoot
? FallbackMode.BLOCKING_STATIC_RENDER
: FallbackMode.PRERENDER
}
}
// Root parameters retain their existing blocking inference. Keep walking
// above so a later explicit not-found can still reject the whole match.
return hasInferredBlockingRoot
? FallbackMode.BLOCKING_STATIC_RENDER
: inferredFallbackMode
}
export function validateParamMatchingParams(
page: string,
paramMatching: Readonly<ParamMatching>,
generatedParamNames: ReadonlySet<string>,
missingParamNames: ReadonlySet<string>,
pathnameSegments: ReadonlyArray<{ readonly paramName: string }>,
output: 'export' | 'standalone' | undefined
): void {
let dynamicParamName: string | undefined
for (const { paramName } of pathnameSegments) {
const mode = paramMatching[paramName]
if (mode === 'dynamic') dynamicParamName = paramName
if (dynamicParamName && generatedParamNames.has(paramName)) {
throw new Error(
`Route "${page}" cannot prerender parameter "${paramName}" because parameter "${dynamicParamName}" is configured as "dynamic".`
)
}
if (mode === 'not-found' && missingParamNames.has(paramName)) {
throw new Error(
`Route "${page}" configures parameter "${paramName}" as "not-found", but generateStaticParams returned a result without that parameter.`
)
}
if (output === 'export' && mode !== 'not-found') {
throw new Error(
`Route "${page}" must configure parameter "${paramName}" as "not-found" when using parameter matching with "output: export".`
)
}
}
}
import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params'
import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
import type { ParamMatching } from '../segment-config/app/app-segments'
type StaticPrerenderedRoute = {
readonly params: Params
......@@ -10,6 +11,7 @@ type StaticPrerenderedRoute = {
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined
remainingPrerenderableParams?: undefined
readonly isPrerenderOutput?: undefined
/**
* When enabled, the route will be rendered with diagnostics enabled which
......@@ -45,6 +47,13 @@ type FallbackPrerenderedRoute = {
readonly fallbackRootParams: readonly string[]
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/**
* False when this candidate renders only for build-time hints or static-shell
* validation, without providing a fallback artifact.
* It must not be registered as a concrete prerender cache output.
*/
readonly isPrerenderOutput?: false
/**
* When enabled, the route will be rendered with diagnostics enabled which
* will error the build if the route that is generated is empty.
......@@ -76,6 +85,12 @@ export type PrerenderRouteMatcher = {
readonly pathname: string
readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined
/**
* The first unresolved prerenderable parameter has no explicit policy.
* Its trial fallback becomes blocking if rendering produces an empty shell,
* independently of whether that shell also requires instant validation.
*/
readonly isFallbackModeInferred?: true
readonly fallbackRootParams: readonly string[]
readonly remainingPrerenderableParams?: readonly FallbackRouteParam[]
}
......@@ -88,4 +103,13 @@ export type StaticPathsResult = {
/** Logical request matchers, independent of the artifacts rendered for them. */
prerenderRouteMatchers?: PrerenderRouteMatcher[]
/** Explicit policies after inheritance, before build-time inference. */
paramMatching?: ParamMatching
/**
* DEV only: the first explicitly configured fallback parameter and every
* parameter after it remain unknown during staged rendering and validation.
*/
explicitFallbackRouteParams?: readonly FallbackRouteParam[]
}
......@@ -645,6 +645,9 @@ export function createAppPageEntrypoint({
let shellCacheKey: string | null = null
if (
nextConfig.cacheComponents &&
// A closed matcher has no fallback shell. Its generated outputs must
// retain their concrete cache keys.
prerenderInfo?.fallback !== false &&
// Never-prerenderable params must stay out of the key even when Partial
// Prefetching is disabled.
(nextConfig.partialPrefetching ||
......@@ -941,10 +944,15 @@ export function createAppPageEntrypoint({
// URLs. Read the current manifest here because dev updates it as
// routes compile.
notFoundParams:
prerenderManifest.dynamicRoutes[normalizedSrcPage]?.fallback ===
(routeModule.isDev
? getRequestMeta(req, 'devNotFoundParams')
: undefined) ??
prerenderManifest.dynamicRoutes[normalizedSrcPage]
?.notFoundParams ??
(prerenderManifest.dynamicRoutes[normalizedSrcPage]?.fallback ===
false
? routeParamNames
: undefined,
: undefined),
incrementalCache,
cacheLifeProfiles: nextConfig.cacheLife,
staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,
......@@ -1181,6 +1189,7 @@ export function createAppPageEntrypoint({
prerenderInfo?.fallback === null &&
// TODO(ensure-static): express this in a cleaner way
!isEnsureStaticPage &&
!prerenderInfo.isExplicitlyBlocking &&
!hasOmittedConcreteFallbackParam &&
!hasUnresolvedRootFallbackParams &&
remainingPrerenderableParams.length > 0
......@@ -1216,6 +1225,10 @@ export function createAppPageEntrypoint({
}
if (
// Ordinary dev requests always use the request-specific render
// below. Only production, forced background work, and explicit
// shell debugging may enter fallback prerender handling.
(isProduction || forceStaticRender || isDebugPrerender) &&
!isMinimalMode &&
fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER &&
staticPathKey &&
......@@ -1742,6 +1755,13 @@ export function createAppPageEntrypoint({
}
const handleResponse = async (span?: Span): Promise<null | void> => {
// Development evaluates the configured policy without emitting its
// production matchers. Use that outcome at the same admission boundary.
const devParamMatchingRejected =
routeModule.isDev &&
!isDebugPrerender &&
getRequestMeta(req, 'devParamMatchingRejected')
// Decide whether this URL is allowed before consulting ISR. An exact
// build path remains valid even when its cached result is missing, and
// the most specific matched route controls whether other paths may be
......@@ -1753,8 +1773,8 @@ export function createAppPageEntrypoint({
!isDraftMode &&
!isPossibleServerAction &&
pageIsDynamic &&
prerenderInfo?.fallback === false &&
!isPrerendered
(devParamMatchingRejected ||
(prerenderInfo?.fallback === false && !isPrerendered))
) {
if (nextConfig.adapterPath) {
return await render404()
......
......@@ -63,7 +63,10 @@ import type { PageExtensions } from './page-extensions-type'
import type { FallbackMode } from '../lib/fallback'
import type { OutgoingHttpHeaders } from 'http'
import type { AppSegmentConfig } from './segment-config/app/app-segment-config'
import type { AppSegment } from './segment-config/app/app-segments'
import type {
AppSegment,
ParamMatching,
} from './segment-config/app/app-segments'
import { collectSegments } from './segment-config/app/app-segments'
import { createIncrementalCache } from '../export/helpers/create-incremental-cache'
import { collectRootParamKeys } from './segment-config/app/collect-root-param-keys'
......@@ -79,7 +82,11 @@ import type {
AppRouteModule,
AppRouteRouteModule,
} from '../server/route-modules/app-route/module'
import type { FunctionsConfigManifest, ManifestRoute } from './index'
import type {
FunctionsConfigManifest,
ManifestRoute,
PrerenderManifest,
} from './index'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { parseNormalizedAppRoute } from '../shared/lib/router/routes/app'
import { getStaticMetadataPrerenderPathname } from '../lib/metadata/get-metadata-route'
......@@ -593,6 +600,93 @@ export async function printTreeView(
print()
}
type PrerenderMatcherDigestEntry = {
behavior: 'not-found' | 'blocking' | 'fallback' | 'prerender'
pathname: string
}
function countDynamicSegments(pathname: string): number {
return pathname.match(/\[[^/]+\]/g)?.length ?? 0
}
/** Prints the concrete request matchers emitted for the experimental API. */
export function printPrerenderMatchers(
prerenderManifest: Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>,
emittedDynamicRoutes: ReadonlyArray<DynamicManifestRoute>
): void {
const sourceRoutes = new Set<string>()
for (const route of Object.values(prerenderManifest.dynamicRoutes)) {
if (route.fallbackSourceRoute) {
sourceRoutes.add(route.fallbackSourceRoute)
}
}
for (const route of Object.values(prerenderManifest.routes)) {
if (route.srcRoute) {
sourceRoutes.add(route.srcRoute)
}
}
if (sourceRoutes.size === 0) return
print(underline('Experimental parameter matching'))
print('More-specific rows override broader rows for the same request.')
print()
for (const sourceRoute of [...sourceRoutes].sort()) {
const matchers = Object.entries(prerenderManifest.dynamicRoutes)
.filter(
([pathname, route]) =>
pathname === sourceRoute || route.fallbackSourceRoute === sourceRoute
)
.map<PrerenderMatcherDigestEntry>(([pathname, route]) => ({
behavior:
route.fallback === false
? 'not-found'
: route.fallback === null
? 'blocking'
: 'fallback',
pathname,
}))
.sort(
(a, b) =>
countDynamicSegments(b.pathname) - countDynamicSegments(a.pathname) ||
a.pathname.localeCompare(b.pathname)
)
const prerenders = Object.entries(prerenderManifest.routes)
.filter(([, route]) => route.srcRoute === sourceRoute)
.map<PrerenderMatcherDigestEntry>(([pathname]) => ({
behavior: 'prerender',
pathname,
}))
.sort((a, b) => a.pathname.localeCompare(b.pathname))
const entries = [...matchers, ...prerenders]
const width = Math.max(...entries.map(({ behavior }) => behavior.length))
print(sourceRoute)
entries.forEach(({ behavior, pathname }, index) => {
print(
` ${index === entries.length - 1 ? '└' : '├'} ${behavior.padEnd(width)} ${pathname}`
)
})
print()
}
print(underline('Emitted dynamic route patterns'))
print('These are the patterns available to deployment routing metadata.')
print()
for (const sourceRoute of [...sourceRoutes].sort()) {
const patterns = emittedDynamicRoutes.filter(
(route) => route.page === sourceRoute || route.sourcePage === sourceRoute
)
print(`${sourceRoute} (${patterns.length})`)
patterns.forEach((route, index) => {
print(` ${index === patterns.length - 1 ? '└' : '├'} ${route.page}`)
})
print()
}
}
export function printCustomRoutes({
redirects,
rewrites,
......@@ -678,6 +772,7 @@ type PageIsStaticResult = {
hasStaticProps?: boolean
prerenderedRoutes: PrerenderedRoute[] | undefined
prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined
paramMatching: ParamMatching | undefined
prerenderFallbackMode: FallbackMode | undefined
rootParamKeys: readonly string[] | undefined
isNextImageImported?: boolean
......@@ -753,6 +848,7 @@ export async function isPageStatic({
prerenderFallbackMode: undefined,
prerenderedRoutes: undefined,
prerenderRouteMatchers: undefined,
paramMatching: undefined,
rootParamKeys: undefined,
hasStaticProps: false,
hasServerProps: false,
......@@ -780,6 +876,7 @@ export async function isPageStatic({
let componentsResult: LoadComponentsReturnType
let prerenderedRoutes: PrerenderedRoute[] | undefined
let prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined
let paramMatching: ParamMatching | undefined
let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppSegmentConfig = {}
let rootParamKeys: readonly string[] | undefined
......@@ -843,9 +940,9 @@ export async function isPageStatic({
const ComponentMod: AppPageModule | AppRouteModule =
componentsResult.ComponentMod
let segments: AppSegment[]
let collectedSegments: Awaited<ReturnType<typeof collectSegments>>
try {
segments = await collectSegments(
collectedSegments = await collectSegments(
// We know this is an app page or app route module because we
// checked above that the page type is 'app'.
routeModule as AppPageRouteModule | AppRouteRouteModule,
......@@ -856,6 +953,7 @@ export async function isPageStatic({
cause: err,
})
}
const { segments, segmentTree } = collectedSegments
appConfig =
originalAppPath === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
......@@ -908,6 +1006,7 @@ export async function isPageStatic({
;({
prerenderedRoutes,
prerenderRouteMatchers,
paramMatching,
fallbackMode: prerenderFallbackMode,
} = await buildAppStaticPaths({
dir,
......@@ -919,6 +1018,7 @@ export async function isPageStatic({
durableUseCacheEntries,
staticPageGenerationTimeout,
segments,
segmentTree,
distDir,
requestHeaders: {},
isrFlushToDisk,
......@@ -1006,6 +1106,7 @@ export async function isPageStatic({
prerenderFallbackMode,
prerenderedRoutes,
prerenderRouteMatchers,
paramMatching,
rootParamKeys,
hasStaticProps,
hasServerProps,
......
......@@ -71,6 +71,7 @@ checkFields<Diff<{
}
config?: {}
generateStaticParams?: Function
${options.type === 'route' ? '' : 'unstable_paramMatching?: {}\n unstable_generateParamMatching?: Function'}
instant?: InstantConfigForTypeCheckInternal
prefetch?: Prefetch
ensureStatic?: EnsureStatic
......
......@@ -413,7 +413,9 @@ export interface UnstableCacheStore extends CommonCacheStore {
*/
export type CacheStore = UseCacheStore | UnstableCacheStore
export type BuildTimeGeneratorName = 'generateStaticParams'
export type BuildTimeGeneratorName =
| 'generateStaticParams'
| 'unstable_generateParamMatching'
export interface BuildTimeGeneratorStore extends CommonWorkUnitStore {
readonly type: 'build-time-generator'
......
......@@ -151,15 +151,20 @@ import {
} from './after/builtin-request-context'
import { NextRequestHint } from './web/adapter'
import type { RouteModule } from './route-modules/route-module'
import { type FallbackMode, parseFallbackField } from '../lib/fallback'
import { FallbackMode, parseFallbackField } from '../lib/fallback'
import { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segment-prefix-rsc'
import { shouldServeStreamingMetadata } from './lib/streaming-metadata'
import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import { decodePathParams } from './lib/router-utils/decode-path-params'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import { fixMojibake } from './lib/fix-mojibake'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control'
import type { PrerenderedRoute } from '../build/static-paths/types'
import type {
PrerenderRouteMatcher,
PrerenderedRoute,
StaticPathsResult,
} from '../build/static-paths/types'
import {
createOpaqueFallbackRouteParams,
getStagedFallbackParams,
......@@ -2304,11 +2309,7 @@ export default abstract class Server<
requestHeaders: import('./lib/incremental-cache').IncrementalCache['requestHeaders']
page: string
isAppPath: boolean
}): Promise<{
staticPaths?: string[]
prerenderedRoutes?: PrerenderedRoute[]
fallbackMode?: FallbackMode
}> {
}): Promise<Partial<StaticPathsResult> & { staticPaths?: string[] }> {
// Read whether or not fallback should exist from the manifest.
const fallbackField =
this.getPrerenderManifest().dynamicRoutes[pathname]?.fallback
......@@ -2748,13 +2749,35 @@ export default abstract class Server<
}
if (isAppPath && this.nextConfig.cacheComponents) {
if (pathsResults.prerenderedRoutes?.length) {
// The source selection includes concrete routes with no fallback
// params. Otherwise it could choose a generic fallback for a fully
// generated URL.
let matchedRoute: PrerenderedRoute | undefined
for (const route of pathsResults.prerenderedRoutes) {
if (!getRouteRegex(route.pathname).re.test(urlPathname)) {
const paramMatching = pathsResults.paramMatching
if (paramMatching !== undefined) {
// Explicit fallback and blocking policies describe how production
// prerenders are selected. Normal dev requests still render
// dynamically; only an explicit not-found match changes their
// foreground behavior.
addRequestMeta(req, 'devParamMatchingRejected', false)
addRequestMeta(
req,
'devNotFoundParams',
Object.keys(paramMatching).filter(
(name) => paramMatching[name] === 'not-found'
)
)
}
if (
pathsResults.prerenderedRoutes?.length ||
pathsResults.prerenderRouteMatchers?.length
) {
// Build-time pathnames are decoded. Match the decoded rewrite
// destination, not the original encoded URL, just as in production.
const decodedPathname = decodePathParams(resolvedUrlPathname)
// Match both build-time prerenders and routes that have no
// build-time output, such as an explicit blocking match.
let matchedRoute: PrerenderedRoute | PrerenderRouteMatcher | undefined
for (const route of pathsResults.prerenderedRoutes ?? []) {
if (!getRouteRegex(route.pathname).re.test(decodedPathname)) {
continue
}
if (
......@@ -2765,10 +2788,29 @@ export default abstract class Server<
matchedRoute = route
}
}
for (const route of pathsResults.prerenderRouteMatchers ?? []) {
if (!getRouteRegex(route.pathname).re.test(decodedPathname)) {
continue
}
if (
matchedRoute === undefined ||
route.fallbackRouteParams.length <
(matchedRoute.fallbackRouteParams?.length ?? 0)
) {
matchedRoute = route
}
}
if (
paramMatching !== undefined &&
matchedRoute?.fallbackMode === FallbackMode.NOT_FOUND
) {
addRequestMeta(req, 'devParamMatchingRejected', true)
}
if (matchedRoute) {
// Explicit shell requests render the matched artifact. Ordinary
// requests stage and validate the same required or completed shell
// target.
// Shell requests keep the matched route's fallback params unknown.
// Ordinary requests use stagedFallbackParams below to determine
// which params resolve in the static phase.
addRequestMeta(
req,
'fallbackRouteParams',
......@@ -2778,11 +2820,29 @@ export default abstract class Server<
)
: null
)
addRequestMeta(
req,
'stagedFallbackParams',
getStagedFallbackParams(matchedRoute)
)
let stagedFallbackParams = getStagedFallbackParams({
...matchedRoute,
// A match without a build-time prerender has no shell validation
// metadata. With false, getStagedFallbackParams lets remaining
// prerenderable params resolve in the static phase; params that
// cannot be prerendered still wait for the dynamic phase.
throwOnEmptyStaticShell:
'throwOnEmptyStaticShell' in matchedRoute
? matchedRoute.throwOnEmptyStaticShell
: false,
})
if (pathsResults.explicitFallbackRouteParams) {
// An explicit fallback must work even when its params are
// unknown. Preserve that boundary for fully generated URLs too,
// without losing holes in a required partial source shell.
stagedFallbackParams = new Map([
...(stagedFallbackParams ?? []),
...(createOpaqueFallbackRouteParams(
pathsResults.explicitFallbackRouteParams
) ?? []),
])
}
addRequestMeta(req, 'stagedFallbackParams', stagedFallbackParams)
}
}
}
......
......@@ -81,7 +81,6 @@ import {
} from '../lib/router-utils/instrumentation-globals.external'
import type { PrerenderManifest } from '../../build'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import type { PrerenderedRoute } from '../../build/static-paths/types'
import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'
......@@ -733,11 +732,7 @@ export default class DevServer extends Server {
requestHeaders: IncrementalCache['requestHeaders']
page: string
isAppPath: boolean
}): Promise<{
prerenderedRoutes?: PrerenderedRoute[]
staticPaths?: string[]
fallbackMode?: FallbackMode
}> {
}): ReturnType<Server['getStaticPaths']> {
// we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode
......@@ -793,7 +788,12 @@ export default class DevServer extends Server {
[]
)
.then(async (res) => {
const { prerenderedRoutes, fallbackMode: fallback } = res.value
const {
prerenderedRoutes,
prerenderRouteMatchers,
fallbackMode: fallback,
paramMatching,
} = res.value
if (isAppPath) {
if (this.nextConfig.output === 'export') {
......@@ -825,17 +825,13 @@ export default class DevServer extends Server {
}
}
const value: {
staticPaths: string[] | undefined
prerenderedRoutes: PrerenderedRoute[] | undefined
fallbackMode: FallbackMode | undefined
} = {
const value = {
...res.value,
staticPaths: prerenderedRoutes?.map((route) => route.pathname),
prerenderedRoutes,
fallbackMode: fallback,
}
if (
paramMatching === undefined &&
res.value?.fallbackMode !== undefined &&
// This matches the hasGenerateStaticParams logic we do during build.
(!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))
......@@ -856,9 +852,10 @@ export default class DevServer extends Server {
// the route whose pathname matches the page pattern (e.g.
// /dynamic-params/[slug]) and has fallback route params describing
// which params are unknown at build time.
const fallbackPrerenderedRoute = prerenderedRoutes?.find(
const fallbackRoute =
prerenderRouteMatchers?.find(
(route) => route.pathname === pathname
)
) ?? prerenderedRoutes?.find((route) => route.pathname === pathname)
existingManifest.dynamicRoutes[pathname] = {
dataRoute: null,
......@@ -868,8 +865,8 @@ export default class DevServer extends Server {
fallbackExpire: undefined,
fallbackHeaders: undefined,
fallbackStatus: undefined,
fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,
fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,
fallbackRootParams: fallbackRoute?.fallbackRootParams,
fallbackRouteParams: fallbackRoute?.fallbackRouteParams,
fallbackSourceRoute: pathname,
prefetchDataRoute: undefined,
prefetchDataRouteRegex: undefined,
......
......@@ -114,7 +114,7 @@ export async function loadStaticPaths({
if (isAppPath) {
const routeModule = components.routeModule
const segments = await collectSegments(
const { segments, segmentTree } = await collectSegments(
// We know this is an app page or app route module because we checked
// above that the page type is 'app'.
routeModule as AppPageRouteModule | AppRouteRouteModule,
......@@ -147,6 +147,7 @@ export async function loadStaticPaths({
route,
cacheComponents: config.cacheComponents,
segments,
segmentTree,
distDir,
requestHeaders,
cacheHandler,
......
......@@ -429,6 +429,33 @@ declare module 'next/form' {
`
}
// Object literals and unannotated generator returns widen their mode values to
// string. Runtime validation checks those values; generated types still enforce
// the parameter scope and mutually exclusive export forms. Users can opt into
// contextual mode checking with `satisfies ParamMatching` from 'next'.
const PRERENDER_MATCHER_TYPE_DEFINITIONS = `type ParamMatchFragment<Route extends keyof ParamMap> = Partial<Record<keyof ParamMap[Route], string>>
type ParamMatchingExports<Route extends keyof ParamMap> =
| { unstable_paramMatching?: ParamMatchFragment<Route>; unstable_generateParamMatching?: never }
| { unstable_paramMatching?: never; unstable_generateParamMatching?: () => Promise<ParamMatchFragment<Route>> | ParamMatchFragment<Route> }
`
function getPrerenderMatcherKeyValidation(
route: string | undefined,
type: string
): string {
return route && (type === 'AppPageConfig' || type === 'LayoutConfig')
? `
type __ParamMatchingValue =
typeof handler extends { unstable_paramMatching: infer Matcher } ? Matcher :
typeof handler extends { unstable_generateParamMatching: (...args: any[]) => infer Matcher } ? Awaited<Matcher> : {}
type __InvalidParamMatchingKeys = Exclude<keyof __ParamMatchingValue, keyof ParamMap[${JSON.stringify(route)}]>
type __AssertNoInvalidParamMatchingKeys<Invalid extends never> = Invalid
const __paramMatchingKeyCheck: __AssertNoInvalidParamMatchingKeys<__InvalidParamMatchingKeys> | undefined = undefined
void __paramMatchingKeyCheck`
: ''
}
export function generateValidatorFile(
routesManifest: RouteTypesManifest
): string {
......@@ -470,6 +497,10 @@ export function generateValidatorFile(
type === 'RouteHandlerConfig')
? `${type}<${JSON.stringify(route)}>`
: type
const matcherKeyValidation = getPrerenderMatcherKeyValidation(
route,
type
)
// NOTE: we previously used `satisfies` here, but it's not supported by TypeScript 4.8 and below.
// If we ever raise the TS minimum version, we can switch back.
......@@ -481,6 +512,7 @@ export function generateValidatorFile(
importPath.replace(/\.tsx?$/, '.js')
)})
type __Check = __IsExpected<typeof handler>
${matcherKeyValidation}
// @ts-ignore
type __Unused = __Check
}`
......@@ -520,6 +552,10 @@ export function generateValidatorFile(
// Build type definitions based on what's actually used
let typeDefinitions = ''
if (appPageValidations || layoutValidations) {
typeDefinitions += PRERENDER_MATCHER_TYPE_DEFINITIONS
}
if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.ComponentType<{ params: Promise<ParamMap[Route]> } & any> | ((props: { params: Promise<ParamMap[Route]> } & any) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>)
......@@ -534,7 +570,7 @@ export function generateValidatorFile(
) => Promise<any> | any
metadata?: any
viewport?: any
}
} & ParamMatchingExports<Route>
`
}
......@@ -574,7 +610,7 @@ export function generateValidatorFile(
) => Promise<any> | any
metadata?: any
viewport?: any
}
} & ParamMatchingExports<Route>
`
}
......@@ -714,6 +750,10 @@ export function generateValidatorFileStrict(
type === 'RouteHandlerConfig')
? `${type}<${JSON.stringify(route)}>`
: type
const matcherKeyValidation = getPrerenderMatcherKeyValidation(
route,
type
)
return `// Validate ${filePath}
{
......@@ -721,6 +761,7 @@ export function generateValidatorFileStrict(
importPath.replace(/\.tsx?$/, '.js')
)})
handler satisfies ${typeWithRoute}
${matcherKeyValidation}
}`
})
.join('\n\n')
......@@ -758,6 +799,10 @@ export function generateValidatorFileStrict(
// Build type definitions based on what's actually used
let typeDefinitions = ''
if (appPageValidations || layoutValidations) {
typeDefinitions += PRERENDER_MATCHER_TYPE_DEFINITIONS
}
if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.JSXElementConstructor<PageProps<Route>>
......@@ -772,7 +817,7 @@ export function generateValidatorFileStrict(
) => Promise<any> | any
metadata?: any
viewport?: any
}
} & ParamMatchingExports<Route>
`
}
......@@ -812,7 +857,7 @@ export function generateValidatorFileStrict(
) => Promise<any> | any
metadata?: any
viewport?: any
}
} & ParamMatchingExports<Route>
`
}
......
......@@ -344,6 +344,12 @@ export interface RequestMeta {
*/
fallbackRouteParams?: OpaqueFallbackRouteParams | null
/** DEV only: parameter matching rejected this request as not found. */
devParamMatchingRejected?: boolean
/** DEV only: closed parameters, including for successful allowed values. */
devNotFoundParams?: readonly string[]
/**
* DEV only: Request timings in process.hrtime.bigint()
*/
......
......@@ -15,6 +15,8 @@ export const NEXT_TS_ERRORS = {
export const ALLOWED_EXPORTS = [
'config',
'generateStaticParams',
'unstable_paramMatching',
'unstable_generateParamMatching',
'metadata',
'generateMetadata',
'viewport',
......
......@@ -18,6 +18,7 @@ import type {
NextApiHandler,
} from './shared/lib/utils'
import type { GetStaticPathsFallback } from './lib/fallback'
import type { ParamMatchingMode } from './build/segment-config/app/app-segments'
import type { NextApiRequestCookies } from './server/api-utils'
......@@ -42,6 +43,15 @@ export type {
export type { Instant } from './build/segment-config/app/app-segment-config'
/**
* Optional contextual typing for parameter matching exports. Use
* `satisfies ParamMatching` to check modes without widening the object's keys,
* or provide parameter names for an explicit type annotation.
*/
export type ParamMatching<ParamName extends string = string> = Partial<
Record<ParamName, ParamMatchingMode>
>
export type { Instrumentation } from './server/instrumentation/types'
export type {
RouterTransitionType,
......
import { Suspense } from 'react'
export async function unstable_generateParamMatching() {
return {
top: 'blocking',
bottom: 'fallback',
} as const
}
export function generateStaticParams() {
return [
{ lang: 'en', top: 't1', bottom: 'b1' },
{ lang: 'es', top: 't1', bottom: 'b1' },
]
}
async function Params({
params,
}: {
params: Promise<{ lang: string; top: string; bottom: string }>
}) {
const { lang, top, bottom } = await params
return <p id="catalog-params">{`${lang}/${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="catalog-shell">catalog shell</p>}>
<Params params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
lang: 'not-found',
} as const
export default function LangLayout({ children }: { children: ReactNode }) {
return children
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'fallback',
bottom: 'dynamic',
} as const
export function generateStaticParams() {
return [{ lang: 'en', top: 't1' }]
}
async function Params({
params,
}: {
params: Promise<{ lang: string; top: string; bottom: string }>
}) {
const { lang, top, bottom } = await params
return <p id="preview-params">{`${lang}/${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="preview-shell">preview shell</p>}>
<Params params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = { top: 'blocking' } as const
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'blocking',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="blocking-only-params">{`${top}/${bottom}`}</p>
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'fallback',
bottom: 'dynamic',
} as const
export function generateStaticParams() {
return [{ top: 't1' }]
}
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="dynamic-suffix-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="dynamic-suffix-shell">dynamic shell</p>}>
<Params params={params} />
</Suspense>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'fallback',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="fallback-only-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="fallback-only-shell">fallback shell</p>}>
<Params params={params} />
</Suspense>
)
}
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="inferred-empty-params">{`${top}/${bottom}`}</p>
}
import { Suspense } from 'react'
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="inferred-full-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="inferred-full-shell">inferred full shell</p>}>
<Params params={params} />
</Suspense>
)
}
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="inferred-hole-blocking-params">{`${top}/${bottom}`}</p>
}
import { Suspense, type ReactNode } from 'react'
export default async function TopLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return (
<section data-top={top}>
<Suspense
fallback={<p id="inferred-hole-blocking-shell">waiting for bottom</p>}
>
{children}
</Suspense>
</section>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="inferred-hole-fallback-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense
fallback={<p id="inferred-hole-fallback-shell">waiting for params</p>}
>
<Params params={params} />
</Suspense>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="no-example-blocking-fallback-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense
fallback={<p id="no-example-blocking-fallback-shell">no example shell</p>}
>
<Params params={params} />
</Suspense>
)
}
export const instant = false
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'dynamic',
} as const
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="no-example-blocking-params">{`${top}/${bottom}`}</p>
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'fallback',
bottom: 'dynamic',
} as const
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="no-example-fallback-params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p id="no-example-fallback-shell">no example shell</p>}>
<Params params={params} />
</Suspense>
)
}
export const unstable_paramMatching = {
top: 'not-found',
bottom: 'not-found',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="not-found-only-params">{`${top}/${bottom}`}</p>
}
export default function Page() {
return <p>prerender matching</p>
}
export const unstable_paramMatching = {
lang: 'blocking',
category: 'blocking',
} as const
export default async function Page({
params,
}: {
params: Promise<{ lang: string; category: string }>
}) {
const { lang, category } = await params
return <p id="specificity-loosen-params">{`${lang}/${category}`}</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
category: 'not-found',
} as const
export function generateStaticParams() {
return [{ lang: 'en', category: 'shoes' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_paramMatching = {
lang: 'not-found',
category: 'not-found',
} as const
export function generateStaticParams() {
return [{ lang: 'en', category: 'shoes' }]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string; category: string }>
}) {
const { lang, category } = await params
return <p id="specificity-tighten-params">{`${lang}/${category}`}</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
lang: 'blocking',
} as const
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_paramMatching = { lang: 'fallback' }
export default async function Page({ params }) {
return <p>{JSON.stringify(await params)}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
parts: 'fallback',
} as const
export function generateStaticParams() {
return [{ parts: ['known', 'deep'] }]
}
async function Params({
params,
}: {
params: Promise<{ lang: string; parts: string[] }>
}) {
const { lang, parts } = await params
return <p id="catch-all">{`${lang}/${parts.join('/')}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; parts: string[] }>
}) {
return (
<Suspense fallback={<p id="catch-all-shell">catch-all shell</p>}>
<Params params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
lang: 'not-found',
} as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = {
parts: 'not-found',
} as const
export function generateStaticParams() {
return [{ parts: [] }, { parts: ['known', 'deep'] }]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string; parts?: string[] }>
}) {
const { lang, parts = [] } = await params
return <p id="optional-catch-all">{`${lang}/${parts.join('/')}`}</p>
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
item: 'fallback',
} as const
async function Params({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
const { lang, item } = await params
return <p id="left">{`left:${lang}/${item}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
return (
<Suspense fallback={<p id="left-shell">left shell</p>}>
<Params params={params} />
</Suspense>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
item: 'fallback',
} as const
async function Params({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
const { lang, item } = await params
return <p id="right">{`right:${lang}/${item}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
return (
<Suspense fallback={<p id="right-shell">right shell</p>}>
<Params params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ item: 'known' }]
}
export default function Layout({
children,
left,
right,
}: {
children: ReactNode
left: ReactNode
right: ReactNode
}) {
return (
<main>
{children}
{left}
{right}
</main>
)
}
import { Suspense } from 'react'
async function Params({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
const { lang, item } = await params
return <p id="children">{`children:${lang}/${item}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; item: string }>
}) {
return (
<Suspense fallback={<p id="children-shell">children shell</p>}>
<Params params={params} />
</Suspense>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'blocking',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <p>{bottom}</p>
}
import type { ReactNode } from 'react'
export default async function TopLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return <section data-top={top}>{children}</section>
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Bottom({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <p>{bottom}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p>bottom fallback</p>}>
<Bottom params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export default async function TopLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return <section data-top={top}>{children}</section>
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'fallback',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Bottom({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <p>{bottom}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p>bottom fallback</p>}>
<Bottom params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export default async function TopLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return <section data-top={top}>{children}</section>
}
import { Suspense } from 'react'
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
async function Bottom({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <p>{bottom}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<Suspense fallback={<p>bottom fallback</p>}>
<Bottom params={params} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export default async function TopLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return <section data-top={top}>{children}</section>
}
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
export const unstable_paramMatching = {
top: 'dynamic',
bottom: 'dynamic',
}
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Page({ params }) {
return <p>{JSON.stringify(await params)}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
}
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default async function Page({ params }) {
const { top, bottom } = await params
return <p>{`${top}/${bottom}`}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = { lang: 'fallback' }
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default async function Page({ params }) {
return <p>{JSON.stringify(await params)}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
module.exports = {
cacheComponents: true,
output: 'export',
}
export const unstable_paramMatching = { lang: 'not-found' }
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default async function Page({ params }) {
return <p>{JSON.stringify(await params)}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { PolicyPage } from '../../policy-page'
export const unstable_paramMatching = {
slug: 'blocking',
} as const
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return <PolicyPage params={params} policy="blocking" />
}
import { PolicyPage } from '../../policy-page'
export const unstable_paramMatching = {
slug: 'fallback',
} as const
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return <PolicyPage params={params} policy="fallback" />
}
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
function ShellMarker({ policy }: { policy: 'blocking' | 'fallback' }) {
return <p data-shell-marker={policy}>{performance.now().toFixed(3)}</p>
}
async function Params({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <p id="params">{slug}</p>
}
export function PolicyPage({
params,
policy,
}: {
params: Promise<{ slug: string }>
policy: 'blocking' | 'fallback'
}) {
return (
<>
<ShellMarker policy={policy} />
<Suspense fallback={<p id="shell">waiting for params</p>}>
<Params params={params} />
</Suspense>
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
export const unstable_paramMatching = {
lang: 'blocking',
}
export function generateStaticParams() {
return [{ lang: 'en', top: 't1', bottom: 'b1' }]
}
export default async function Page({ params }) {
return <p>{JSON.stringify(await params)}</p>
}
export const unstable_paramMatching = {
top: 'not-found',
}
export default function Layout({ children }) {
return children
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
}
async function Bottom({ params }) {
const { bottom } = await params
return <p>{bottom}</p>
}
export default function Page({ params }) {
return (
<Suspense fallback={<p>unknown bottom</p>}>
<Bottom params={params} />
</Suspense>
)
}
export default async function TopLayout({ children, params }) {
const { top } = await params
return <section data-top={top}>{children}</section>
}
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [{ lang: 'en', category: 'shoes' }]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string; category: string }>
}) {
return <p>{JSON.stringify(await params)}</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
category: 'blocking',
} as const
export default function Layout({ children }: { children: ReactNode }) {
return children
}
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import path from 'node:path'
import type { NextAdapter } from 'next'
import { nextTestSetup } from 'e2e-utils'
import { getDevCliValidationOutput } from 'e2e-utils/instant-validation'
import { retry } from 'next-test-utils'
import {
PrefetchHint,
type PrefetchHints,
} from 'next/dist/shared/lib/app-router-types'
type DynamicRoute = {
fallback: false | null | string
fallbackSourceRoute?: string
throwOnEmptyStaticShell?: boolean
remainingPrerenderableParams?: Array<{
paramName: string
paramType: string
}>
}
describe('parameter matching', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
env: {
NEXT_PRIVATE_DEBUG_PARAM_MATCHING: '1',
},
})
it('inherits closed parameters and lets a page override open policies', async () => {
const inherited = await next.fetch('/en/catalog/t1/items/b2')
expect(inherited.status).toBe(200)
expect(await inherited.text()).toContain('en/t1/b2')
const overridden = await next.fetch('/en/preview/t2/items/b2')
expect(overridden.status).toBe(200)
expect(await overridden.text()).toContain('en/t2/b2')
expect((await next.fetch('/fr/catalog/t1/items/b1')).status).toBe(404)
expect((await next.fetch('/fr/preview/t1/items/b1')).status).toBe(404)
})
it('supports uniform policies and permanently dynamic suffixes', async () => {
for (const [pathname, text] of [
['/fallback-only/t2/items/b2', 't2/b2'],
['/blocking-only/t2/items/b2', 't2/b2'],
['/dynamic-suffix/t2/items/b2', 't2/b2'],
['/no-example-fallback/t2/items/b2', 't2/b2'],
['/no-example-blocking/t2/items/b2', 't2/b2'],
['/no-example-blocking-fallback/t2/items/b2', 't2/b2'],
]) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
expect(await response.text()).toContain(text)
}
expect((await next.fetch('/not-found-only/t1/items/b1')).status).toBe(200)
expect((await next.fetch('/not-found-only/t1/items/b2')).status).toBe(404)
expect((await next.fetch('/not-found-only/t2/items/b2')).status).toBe(404)
})
it('preserves inferred fallback and blocking behavior without configuration', async () => {
const full = await next.fetch('/inferred-full/t2/items/b2')
expect(full.status).toBe(200)
expect(await full.text()).toContain('t2/b2')
const empty = await next.fetch('/inferred-empty/t2/items/b2')
expect(empty.status).toBe(200)
expect(await empty.text()).toContain('t2/b2')
})
it('fills policy holes using the existing shell heuristic', async () => {
const blocking = await next.fetch('/inferred-hole-blocking/t2/items/b2')
expect(blocking.status).toBe(200)
expect(await blocking.text()).toContain('t2/b2')
const fallback = await next.fetch('/inferred-hole-fallback/t2/items/b2')
expect(fallback.status).toBe(200)
expect(await fallback.text()).toContain('t2/b2')
})
it('requires descendants to override every affected explicit policy', async () => {
const tightened = await next.fetch('/specificity-tighten/en/shoes')
expect(tightened.status).toBe(200)
expect(await tightened.text()).toContain('en/shoes')
expect((await next.fetch('/specificity-tighten/en/hats')).status).toBe(404)
expect((await next.fetch('/specificity-tighten/fr/shoes')).status).toBe(404)
const loosened = await next.fetch('/specificity-loosen/fr/hats/details')
expect(loosened.status).toBe(200)
expect(await loosened.text()).toContain('fr/hats')
})
if (isNextStart) {
it.each([
'/no-example-blocking/[top]/items/[bottom]',
'/no-example-blocking-fallback/[top]/items/[bottom]',
])(
'collects build-time hints without publishing a blocking fallback for %s',
async (pathname) => {
const hints = (await next.readJSON(
'.next/server/prefetch-hints.json'
)) as Record<string, PrefetchHints>
const manifest = (await next.readJSON(
'.next/prerender-manifest.json'
)) as {
routes: Record<string, unknown>
dynamicRoutes: Record<string, DynamicRoute>
}
// Neither route has generateStaticParams. The first permits an empty
// shell with instant=false; the second validates its non-empty shell.
// Both still need a build render to collect best-effort prefetch hints.
expect(hints[pathname]).toBeDefined()
const nodes = [hints[pathname]]
for (const node of nodes) {
expect(node.hints & PrefetchHint.PrefetchDisabled).toBe(0)
if (node.slots) nodes.push(...Object.values(node.slots))
}
expect(manifest.dynamicRoutes[pathname].fallback).toBeNull()
expect(manifest.routes[pathname]).toBeUndefined()
}
)
it('only specializes unresolved prerenderable params', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
) as { dynamicRoutes: Record<string, DynamicRoute> }
for (const [pathname, paramNames] of [
// With both params seeded, each shell can fill the remaining suffix.
['/inferred-full/[top]/items/[bottom]', ['top', 'bottom']],
['/inferred-full/t1/items/[bottom]', ['bottom']],
// A permanently dynamic suffix must never be specialized.
['/dynamic-suffix/[top]/items/[bottom]', ['top']],
['/dynamic-suffix/t1/items/[bottom]', []],
// Explicit policies allow specialization without build-time examples,
// including matcher-only prefixes that produce no fallback artifact.
['/no-example-fallback/[top]/items/[bottom]', ['top']],
['/no-example-blocking/[top]/items/[bottom]', ['top']],
[
'/no-example-blocking-fallback/[top]/items/[bottom]',
['top', 'bottom'],
],
] as const) {
expect(manifest.dynamicRoutes[pathname]).toBeDefined()
expect(
manifest.dynamicRoutes[pathname].remainingPrerenderableParams
).toEqual(
paramNames.length > 0
? paramNames.map((paramName) => ({
paramName,
paramType: 'dynamic',
}))
: undefined
)
}
})
it('emits one route matcher for each effective prefix behavior', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
) as {
routes: Record<string, { srcRoute?: string }>
dynamicRoutes: Record<string, DynamicRoute>
}
const sourceRoute = '/[lang]/catalog/[top]/items/[bottom]'
const matchers = Object.fromEntries(
Object.entries(manifest.dynamicRoutes).filter(
([pathname, route]) =>
pathname === sourceRoute ||
route.fallbackSourceRoute === sourceRoute
)
)
expect(matchers[sourceRoute].fallback).toBe(false)
expect(matchers['/en/catalog/[top]/items/[bottom]'].fallback).toBeNull()
expect(typeof matchers['/en/catalog/t1/items/[bottom]'].fallback).toBe(
'string'
)
expect(matchers['/es/catalog/[top]/items/[bottom]'].fallback).toBeNull()
expect(typeof matchers['/es/catalog/t1/items/[bottom]'].fallback).toBe(
'string'
)
// Matcher-only prefixes have no source shell to validate. The explicit
// fallback below them is the required shell, even with a concrete child.
expect(matchers[sourceRoute].throwOnEmptyStaticShell).toBe(false)
expect(
matchers['/en/catalog/[top]/items/[bottom]'].throwOnEmptyStaticShell
).toBe(false)
expect(
matchers['/en/catalog/t1/items/[bottom]'].throwOnEmptyStaticShell
).toBe(true)
expect(manifest.routes['/en/catalog/t1/items/b1']?.srcRoute).toBe(
sourceRoute
)
expect(manifest.routes['/es/catalog/t1/items/b1']?.srcRoute).toBe(
sourceRoute
)
expect(
manifest.dynamicRoutes['/inferred-hole-blocking/[top]/items/[bottom]']
.fallback
).toBeNull()
expect(
typeof manifest.dynamicRoutes[
'/inferred-hole-blocking/t1/items/[bottom]'
].fallback
).toBe('string')
expect(
typeof manifest.dynamicRoutes[
'/inferred-hole-fallback/[top]/items/[bottom]'
].fallback
).toBe('string')
expect(
typeof manifest.dynamicRoutes[
'/inferred-hole-fallback/t1/items/[bottom]'
].fallback
).toBe('string')
expect(
typeof manifest.dynamicRoutes[
'/no-example-fallback/[top]/items/[bottom]'
].fallback
).toBe('string')
expect(
manifest.dynamicRoutes[
'/no-example-blocking-fallback/[top]/items/[bottom]'
].fallback
).toBeNull()
expect(
manifest.dynamicRoutes['/no-example-blocking/[top]/items/[bottom]']
.fallback
).toBeNull()
})
it('prints the effective matching and deployment-pattern digest', () => {
expect(next.cliOutput).toContain('Experimental parameter matching')
expect(next.cliOutput).toContain(
'not-found /[lang]/catalog/[top]/items/[bottom]'
)
expect(next.cliOutput).toContain(
'blocking /en/catalog/[top]/items/[bottom]'
)
expect(next.cliOutput).toContain(
'fallback /en/catalog/t1/items/[bottom]'
)
expect(next.cliOutput).toContain('prerender /en/catalog/t1/items/b1')
expect(next.cliOutput).toContain('/inferred-empty/[top]/items/[bottom]')
expect(next.cliOutput).toContain(
'blocking /inferred-hole-blocking/[top]/items/[bottom]'
)
expect(next.cliOutput).toContain(
'fallback /inferred-hole-blocking/t1/items/[bottom]'
)
expect(next.cliOutput).toContain('Emitted dynamic route patterns')
expect(next.cliOutput).toContain('/[lang]/catalog/[top]/items/[bottom] (')
})
it('uses the existing fallback-false adapter routing contract', async () => {
const { routing, outputs, distDir, repoRoot } = JSON.parse(
await next.readFile('build-complete.json')
) as Parameters<NonNullable<NextAdapter['onBuildComplete']>>[0]
const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
) as {
preview: { previewModeId: string }
}
const sourceRoute = '/[lang]/catalog/[top]/items/[bottom]'
const blockingRoute = '/en/catalog/[top]/items/[bottom]'
const fallbackRoute = '/en/catalog/t1/items/[bottom]'
const routesBySource = new Map(
routing.dynamicRoutes.map((route) => [route.source, route])
)
// Like dynamicParams=false and Pages Router fallback:false, closed
// matchers require the build's Draft Mode bypass cookie. The legacy
// preview-data cookie is not required; normal misses stay closed.
const fallbackFalseHas = [
{
type: 'cookie',
key: '__prerender_bypass',
value: prerenderManifest.preview.previewModeId,
},
]
for (const [pattern, pathname] of [
[sourceRoute, '/fr/catalog/t2/items/b2'],
[blockingRoute, '/en/catalog/t2/items/b2'],
[fallbackRoute, '/en/catalog/t1/items/b2'],
]) {
const emittedRoute = routesBySource.get(pattern)!
expect(emittedRoute).toBeDefined()
expect(emittedRoute.has).toEqual(
pattern === sourceRoute ? fallbackFalseHas : undefined
)
// Canary collapses document, RSC, and segment requests into one
// matcher. The bypass-cookie gate must cover every request form.
const regex = new RegExp(emittedRoute.sourceRegex)
for (const suffix of ['', '.rsc', '.segments/_tree.segment.rsc']) {
expect(pathname + suffix).toMatch(regex)
}
}
const routeSources = routing.dynamicRoutes.map((route) => route.source)
expect(routeSources.indexOf(fallbackRoute)).toBeLessThan(
routeSources.indexOf(blockingRoute)
)
expect(routeSources.indexOf(blockingRoute)).toBeLessThan(
routeSources.indexOf(sourceRoute)
)
// Specialized matchers use the original page module and manifest. They
// do not need synthetic page entrypoints in the deployed function.
const parentOutput = outputs.appPages.find(
(output) => output.pathname === sourceRoute
)!
expect(parentOutput).toBeDefined()
const manifestPath = path.join(distDir, 'app-path-routes-manifest.json')
expect(parentOutput.assets[path.relative(repoRoot, manifestPath)]).toBe(
manifestPath
)
for (const pattern of [blockingRoute, fallbackRoute]) {
const aliasPath = path.join(distDir, 'server/app', `${pattern}/page.js`)
expect(
parentOutput.assets[path.relative(repoRoot, aliasPath)]
).toBeUndefined()
}
// A closed prefix does not make the whole page a build-time allowlist.
// Fully closed pages still retain that restriction.
const seededOutput = outputs.prerenders.find(
(output) => output.pathname === '/en/catalog/t1/items/b1'
)!
expect(seededOutput).toBeDefined()
expect(seededOutput.parentOutputId).toBe(parentOutput.id)
expect(seededOutput.parentFallbackMode).toBeUndefined()
expect(
outputs.prerenders.find(
(output) => output.pathname === '/not-found-only/t1/items/b1'
)?.parentFallbackMode
).toBe(false)
})
}
})
describe('parameter matching complex route shapes', () => {
const { next, isNextStart } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'complex-routes'),
})
it('applies root and catch-all parameter policies in order', async () => {
for (const pathname of [
'/en/catch-all/known/deep',
'/en/catch-all/novel/deep',
]) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
expect(await response.text()).toContain(
`en/${pathname.split('/').slice(3).join('/')}`
)
}
expect((await next.fetch('/fr/catch-all/novel/deep')).status).toBe(404)
})
it('closes both forms of an optional catch-all miss', async () => {
for (const pathname of [
'/en/optional-catch-all',
'/en/optional-catch-all/known/deep',
]) {
expect((await next.fetch(pathname)).status).toBe(200)
}
expect((await next.fetch('/en/optional-catch-all/novel')).status).toBe(404)
expect((await next.fetch('/fr/optional-catch-all')).status).toBe(404)
})
it('merges an agreed policy for a param shared by parallel slots', async () => {
for (const item of ['known', 'novel']) {
const response = await next.fetch(`/en/parallel/${item}`)
expect(response.status).toBe(200)
const html = await response.text()
expect(html).toContain(`children:en/${item}`)
expect(html).toContain(`left:en/${item}`)
expect(html).toContain(`right:en/${item}`)
}
expect((await next.fetch('/fr/parallel/novel')).status).toBe(404)
})
if (isNextStart) {
it('does not print parameter matching diagnostics by default', () => {
expect(next.cliOutput).not.toContain('Experimental parameter matching')
expect(next.cliOutput).not.toContain('Emitted dynamic route patterns')
})
it('emits root-gated matchers for catch-all and parallel routes', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
) as {
dynamicRoutes: Record<string, DynamicRoute>
}
expect(
manifest.dynamicRoutes['/[lang]/catch-all/[...parts]'].fallback
).toBe(false)
expect(
typeof manifest.dynamicRoutes['/en/catch-all/[...parts]'].fallback
).toBe('string')
expect(manifest.dynamicRoutes['/[lang]/parallel/[item]'].fallback).toBe(
false
)
expect(
typeof manifest.dynamicRoutes['/en/parallel/[item]'].fallback
).toBe('string')
})
}
})
describe('parameter matching foreground policy', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'foreground-policy'),
})
if (skipped || isNextDev) {
it.skip('only runs against a production route cache', () => {})
return
}
function readShellMarker(body: string): string {
const match = body.match(/data-shell-marker="[^"]+">([^<]+)</)
expect(match).not.toBeNull()
return match![1]
}
async function render(pathname: string) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
const body = await response.text()
expect(body).toContain(`<p id="params">${pathname.split('/').at(-1)}</p>`)
return { body, marker: readShellMarker(body) }
}
it('generates a distinct shell before returning a blocking miss', async () => {
const first = await render('/blocking/novel-a')
const other = await render('/blocking/novel-b')
expect(other.marker).not.toBe(first.marker)
expect(first.body).not.toContain('<p id="shell">waiting for params</p>')
expect(other.body).not.toContain('<p id="shell">waiting for params</p>')
const repeat = await render('/blocking/novel-a')
expect(repeat.marker).toBe(first.marker)
})
it('returns the shared build shell for a fallback miss', async () => {
const first = await render('/fallback/novel-a')
const other = await render('/fallback/novel-b')
expect(other.marker).toBe(first.marker)
expect(first.body).toContain('<p id="shell">waiting for params</p>')
expect(other.body).toContain('<p id="shell">waiting for params</p>')
})
})
describe('parameter matching ordering validation', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'invalid-order'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skipped', () => {})
return
}
beforeAll(async () => {
if (isNextDev) {
await next.start()
await next.fetch('/en/t1/b1')
} else {
await next.build().catch(() => {})
}
})
it('rejects incoherent policies after layout and page merging', async () => {
await retry(() => {
expect(next.cliOutput).toContain(
'Expected parameters in this order: "not-found", "blocking", "fallback", then "dynamic"'
)
})
})
})
describe('parameter matching dynamic validation', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'dynamic-prerender'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skipped', () => {})
return
}
beforeAll(async () => {
if (isNextDev) {
await next.start()
await next.fetch('/t1/b1')
} else {
await next.build().catch(() => {})
}
})
it('rejects generateStaticParams output at or below a dynamic param', async () => {
await retry(() => {
expect(next.cliOutput).toContain(
'cannot prerender parameter "top" because parameter "top" is configured as "dynamic"'
)
})
})
})
describe('parameter matching type validation', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'type-invalid-param-below'),
skipStart: true,
skipDeployment: true,
})
if (skipped || !isNextStart) {
it.skip('only runs during production builds', () => {})
return
}
beforeAll(async () => {
await next.build().catch(() => {})
})
it('constrains matching keys to params visible to the exporting module', () => {
expect(next.cliOutput).toContain('Failed to type check.')
expect(next.cliOutput).toMatch(
/Type '"category"' does not satisfy the constraint 'never'/
)
})
})
describe('parameter matching without a config opt-in', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'flag-disabled'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skipped', () => {})
return
}
beforeAll(async () => {
await next.start()
})
it('uses the unstable export without a next.config flag', async () => {
expect((await next.fetch('/en')).status).toBe(200)
expect((await next.fetch('/fr')).status).toBe(404)
})
})
describe('parameter matching cache components requirement', () => {
if (process.env.__NEXT_CACHE_COMPONENTS === 'true') {
it.skip('not applicable when Cache Components is forced on', () => {})
return
}
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'cache-components-disabled'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skipped', () => {})
return
}
beforeAll(async () => {
if (isNextDev) {
await next.start()
await next.fetch('/en')
} else {
await next.build().catch(() => {})
}
})
it('requires Cache Components', async () => {
await retry(() => {
expect(next.cliOutput).toContain(
'cannot use parameter matching without enabling `cacheComponents`'
)
})
})
})
describe('parameter matching static export validation', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'export-open-param'),
skipStart: true,
skipDeployment: true,
})
if (skipped || !isNextStart) {
it.skip('only runs during production builds', () => {})
return
}
beforeAll(async () => {
await next.build().catch(() => {})
})
it('requires every exported param to be explicitly closed for now', () => {
expect(next.cliOutput).toContain(
'must configure parameter "lang" as "not-found"'
)
})
})
describe('parameter matching fallback validation', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'empty-fallback'),
skipStart: true,
skipDeployment: true,
})
if (skipped || !isNextStart) {
it.skip('only runs during production builds', () => {})
return
}
beforeAll(async () => {
await next.build().catch(() => {})
})
it('does not downgrade an explicitly configured fallback to blocking', () => {
expect(next.cliOutput).toContain(
'Error occurred prerendering page "/t1/[bottom]"'
)
})
})
describe('parameter matching generic shell validation', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'missing-fallback-seed'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skipped', () => {})
return
}
beforeAll(async () => {
if (isNextDev) {
await next.start()
await next.fetch('/t1/b1')
} else {
await next.build().catch(() => {})
}
})
it('validates the generic blocking shell when no example reaches fallback', async () => {
await retry(() => {
if (isNextDev) {
expect(next.cliOutput).toContain(
'encountered runtime data during prerendering'
)
expect(next.cliOutput).toContain('at TopLayout')
} else {
expect(next.cliOutput).toContain(
'Error occurred prerendering page "/[top]/[bottom]"'
)
}
})
})
})
describe('parameter matching development shell validation', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'dev-shell-validation'),
skipStart: true,
skipDeployment: true,
env: {
NEXT_TEST_LOG_VALIDATION: '1',
},
})
if (skipped || !isNextDev) {
it.skip('only runs in development', () => {})
return
}
beforeAll(async () => {
await next.start()
})
async function renderAndWaitForValidation(pathname: string) {
const outputIndex = next.cliOutput.length
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
return getDevCliValidationOutput(`http://n${pathname}`, () =>
next.cliOutput.slice(outputIndex)
)
}
it('uses the most-specific generated shape for an inferred generated value', async () => {
const inferredKnown = await renderAndWaitForValidation('/inferred/t1/b2')
expect(inferredKnown).not.toContain(
'Error: Route "/inferred/[top]/[bottom]"'
)
})
it('uses the most-specific generated shape for an inferred novel param', async () => {
const inferredNovel = await renderAndWaitForValidation('/inferred/t2/b2')
expect(inferredNovel).not.toContain(
'Error: Route "/inferred/[top]/[bottom]"'
)
})
it('uses the most-specific generated shape when no fallback is configured', async () => {
const blockingOnlyNovel = await renderAndWaitForValidation(
'/blocking-only/t2/b2'
)
expect(blockingOnlyNovel).not.toContain(
'Error: Route "/blocking-only/[top]/[bottom]"'
)
})
it('treats an explicitly blocking param as known', async () => {
const blockingNovel = await renderAndWaitForValidation('/blocking/t2/b2')
expect(blockingNovel).not.toContain(
'Error: Route "/blocking/[top]/[bottom]"'
)
})
it.each(['/fallback/t1/b1', '/fallback/t1/b2', '/fallback/t2/b2'])(
'treats an explicitly fallback param as unknown for %s',
async (pathname) => {
const outputIndex = next.cliOutput.length
await renderAndWaitForValidation(pathname)
// Webpack's formatted stderr can arrive after the stdout validation
// markers. Wait for the error from this request, not their pipe ordering.
await retry(() => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'Error: Route "/fallback/[top]/[bottom]"'
)
})
}
)
})
import fs from 'node:fs/promises'
/** @type {import('next').NextAdapter} */
export default {
name: 'generate-prerender-matching',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
adapterPath: require.resolve('./my-adapter.mjs'),
}
module.exports = nextConfig
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { slug: 'dynamic' }
export default function Page() {
return <p>Static content</p>
}
export const unstable_ensureStatic = 'navigation'
export default function Layout({ children }: { children: React.ReactNode }) {
return children
}
export async function unstable_generateParamMatching() {
return { slug: 'fallback' }
}
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
return <p>Static content</p>
}
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { bottom: 'blocking' }
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return (
<p>
{top}/{bottom}
</p>
)
}
export const unstable_paramMatching = { slug: 'fallback' }
export default function Layout({ children }: { children: React.ReactNode }) {
return children
}
export const unstable_ensureStatic = 'navigation'
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
return <p>Static content</p>
}
export const unstable_ensureStatic = 'navigation'
export const instant = false
export const unstable_paramMatching = { slug: 'fallback' }
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
return <p>Static content</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { slug: 'blocking' }
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return <p>{(await params).slug}</p>
}
export default function Page() {
return <p>hello world</p>
}
export async function unstable_generateParamMatching() {
return { slug: 'fallback' }
}
export default function Page() {
return <p>Sidebar content</p>
}
export default function Layout({ children, sidebar }) {
return (
<>
{children}
{sidebar}
</>
)
}
export const unstable_ensureStatic = 'navigation'
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
return <p>Main content</p>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
export const instant = false
export const unstable_paramMatching = { slug: 'blocking' }
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
return (
<main>
<p>Static content</p>
<Suspense fallback={<p>Loading</p>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic content</p>
}
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { slug: 'fallback' }
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export default function Page() {
// Even a route that does not read params cannot currently serve
// navigation-mode fallbacks.
return <p>Static content</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./param-matching-ensure-static-errors.test')
import { nextTestSetup } from 'e2e-utils'
import {
openRedbox,
waitForRedbox,
getRedboxDescription,
} from 'next-test-utils'
// These apps deliberately reject configuration or static validation and cannot
// be deployed. Build each real route in isolation.
// @force-gate !deploy
describe('param-matching-ensure-static-errors', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
skipStart: true,
})
beforeAll(async () => {
if (isNextDev) {
await next.start()
}
})
async function expectError(
route: string,
pathname: string,
message: string,
redboxState: 'open' | 'collapsed' = 'open'
) {
if (isNextDev) {
const browser = await next.browser(pathname)
if (redboxState === 'collapsed') {
// Static validation is reported as an issue after the dev render;
// configuration errors throw before rendering and open the overlay.
await openRedbox(browser)
} else {
await waitForRedbox(browser)
}
expect(await getRedboxDescription(browser)).toContain(message)
} else {
const result = await next.build({
args: ['--debug-build-paths', `app/${route}/**/page.tsx`],
})
expect(result.cliOutput).not.toContain('did not match any files')
expect(result.cliOutput).toContain(message)
expect(result.exitCode).toBe(1)
}
}
it.each([
['same-page', 'fallback'],
['dynamic', 'dynamic'],
['inherited', 'fallback'],
['generated', 'fallback'],
['instant-false', 'fallback'],
['parallel', 'fallback'],
])(
'rejects %s matching with a useful configuration error',
async (route, mode) => {
await expectError(
route,
`/${route}/seed`,
`Route "/${route}/[slug]" cannot configure parameter "slug" as "${mode}" with \`unstable_ensureStatic = "navigation"\`. Use "blocking" or "not-found" parameter matching, or remove the navigation constraint.`
)
}
)
it('still requires GSP examples for explicitly blocking params', async () => {
await expectError(
'missing',
'/missing/seed',
'Page "/missing/[slug]" is missing `generateStaticParams()`'
)
})
it('still requires every parameter in the GSP result', async () => {
await expectError(
'incomplete',
'/incomplete/t1/b1',
'Every params object must include all dynamic route parameters. Missing: "bottom".'
)
})
it('does not let blocking or instant=false bypass navigation validation', async () => {
await expectError(
'runtime-data',
'/runtime-data/seed',
'on a route that must be fully static',
'collapsed'
)
})
})
export { default } from '../../../param-page'
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { top: 'blocking', bottom: 'blocking' }
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export { default } from '../../../param-page'
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { top: 'not-found' }
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export { default } from '../../../param-page'
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { top: 'not-found', bottom: 'blocking' }
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export { default } from '../../../param-page'
export const unstable_ensureStatic = 'navigation'
export const unstable_paramMatching = { top: 'not-found', bottom: 'not-found' }
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export { default } from '../../../param-page'
export const unstable_ensureStatic = 'navigation'
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = { top: 'fallback' }
export default function Layout({ children }: { children: React.ReactNode }) {
return children
}
export { default } from '../../param-page'
export const unstable_ensureStatic = 'navigation'
export async function unstable_generateParamMatching() {
return { top: 'blocking' }
}
export function generateStaticParams() {
return [{ top: 't1' }]
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/blocking/t2/navigation" prefetch={false}>
Blocking
</Link>
<Link href="/closed-prefix/t1/navigation" prefetch={false}>
Closed prefix
</Link>
</>
)
}
import { Suspense } from 'react'
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom?: string }>
}) {
return (
<main>
<p>Static content</p>
<Suspense fallback={<p id="pending">Waiting for params</p>}>
<Content params={params} />
</Suspense>
</main>
)
}
async function Content({
params,
}: {
params: Promise<{ top: string; bottom?: string }>
}) {
const { top, bottom } = await params
// Only concrete renders get a changing marker. Putting it in the generic
// shell would make the cached HTML disagree with a later resumed render.
return (
<>
<p id="params">{bottom ? `${top}/${bottom}` : top}</p>
<p id="generation">{performance.timeOrigin + performance.now()}</p>
</>
)
}
export { default } from '../../param-page'
export const unstable_ensureStatic = 'prefetch'
export const unstable_paramMatching = { top: 'fallback' }
export function generateStaticParams() {
return [{ top: 't1' }]
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./param-matching-ensure-static.test')
import { nextTestSetup } from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
import type { PrerenderManifest } from 'next/dist/build'
import * as cheerio from 'cheerio'
describe('param-matching-ensure-static', () => {
const { next, isNextDev } = nextTestSetup({ files: __dirname })
it.each([
['/inferred/t1/b1', 't1/b1'],
['/inferred/t2/b2', 't2/b2'],
['/blocking/t1/b1', 't1/b1'],
['/blocking/t2/b2', 't2/b2'],
['/closed-prefix/t1/b1', 't1/b1'],
['/closed-prefix/t1/b2', 't1/b2'],
['/closed-prefix-inferred/t1/b2', 't1/b2'],
['/closed/t1/b1', 't1/b1'],
['/override/t2', 't2'],
])('serves a complete navigation for %s', async (pathname, params) => {
for (const headers of [{}, { rsc: '1' }]) {
const response = await next.fetch(pathname, { headers })
expect(response.status).toBe(200)
const body = await response.text()
expect(body).toContain(params)
if (!isNextDev) {
// Navigation mode must never send a generic shell and resume it,
// even for params that were not in generateStaticParams.
if (!headers.rsc) {
const $ = cheerio.load(body)
expect($('#params').text()).toBe(params)
expect($('#pending')).toHaveLength(0)
// The changing marker makes response equality below distinguish a
// cached prerender from repeated renders of otherwise identical UI.
expect($('#generation')).toHaveLength(1)
}
expect(
await next.fetch(pathname, { headers }).then((r) => r.text())
).toBe(body)
}
}
})
it.each([
'/closed-prefix/t2/b1',
'/closed-prefix-inferred/t2/b1',
'/closed/t1/b2',
'/closed/t2/b1',
])('does not open a not-found parameter in %s', async (pathname) => {
expect((await next.fetch(pathname)).status).toBe(404)
})
it.each([
['/blocking/t2/navigation', 't2/navigation'],
['/closed-prefix/t1/navigation', 't1/navigation'],
])('supports a client navigation to %s', async (pathname, params) => {
const browser = await next.browser('/')
await browser.elementByCss(`a[href="${pathname}"]`).click()
expect(await browser.elementByCss('#params').text()).toBe(params)
await waitForNoRedbox(browser)
})
it('still allows fallback matching with ensureStatic = "prefetch"', async () => {
expect((await next.fetch('/prefetch/novel')).status).toBe(200)
const browser = await next.browser('/prefetch/novel')
expect(await browser.elementByCss('#params').text()).toBe('novel')
await waitForNoRedbox(browser)
})
// The deployment behavior is covered above; these assertions inspect local
// build artifacts to protect the adapter contract as well.
// @force-gate start
it('keeps matchers and generic prefetch data without servable navigation fallbacks', async () => {
const manifest: PrerenderManifest = await next.readJSON(
'.next/prerender-manifest.json'
)
const hints = await next.readJSON('.next/server/prefetch-hints.json')
for (const route of [
'inferred',
'blocking',
'closed-prefix',
'closed-prefix-inferred',
'closed',
]) {
const pattern = `/${route}/[top]/[bottom]`
const matcher = manifest.dynamicRoutes[pattern]
expect(matcher._isEnsureStaticPage).toBe(true)
expect(matcher.fallback).toBe(route.startsWith('closed') ? false : null)
expect(manifest.routes[pattern]).toBeUndefined()
// ensureStatic needs the generic render's segment data even when
// paramMatching would normally omit that blocking/not-found candidate.
expect(hints[pattern]).toBeDefined()
expect(await next.hasFile(`.next/server/app${pattern}.meta`)).toBe(true)
}
for (const route of ['closed-prefix', 'closed-prefix-inferred']) {
expect(manifest.dynamicRoutes[`/${route}/t1/[bottom]`]).toMatchObject({
fallback: null,
_isEnsureStaticPage: true,
})
expect(manifest.routes[`/${route}/t1/b1`]).toBeDefined()
expect(
await next.hasFile(`.next/server/app/${route}/t1/[bottom].meta`)
).toBe(false)
}
})
})
export function generateStaticParams() {
return [{ lang: 'en', top: 't1' }]
}
export default async function Page({ params }) {
const { lang, top } = await params
return <p>{`${lang}/${top}`}</p>
}
export default function Layout({ children }) {
return children
}
import type { ReactNode } from 'react'
import { Suspense } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense fallback={<p>Loading</p>}>{children}</Suspense>
</body>
</html>
)
}
export function unstable_generateParamMatching() {
return { top: 'blocking' }
}
export async function unstable_generateParamMatching() {
return { lang: 'invalid' }
}
export async function unstable_generateParamMatching() {
return null
}
export const unstable_generateParamMatching = { lang: 'blocking' }
async function privateConfig() {
'use cache: private'
return { lang: 'blocking' }
}
export async function unstable_generateParamMatching() {
return privateConfig()
}
export async function unstable_generateParamMatching() {
throw new Error('MATCHER_GENERATOR_FAILURE')
}
export const unstable_paramMatching = { top: 'blocking' }
export function unstable_paramMatching() {
throw new Error('UNEXPECTED_MATCHER_EXECUTION')
}
export const unstable_paramMatching = { lang: 'unsupported' }
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Exercise runtime validation independently of the generated type checks.
typescript: { ignoreBuildErrors: true },
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// These exports deliberately fail validation and cannot produce a deployment.
// @force-gate !deploy
describe('param-matching-exports', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
skipStart: true,
})
const layoutFile = 'app/[lang]/layout.js'
let layout: string
beforeAll(async () => {
layout = await next.readFile(layoutFile)
if (isNextDev) await next.start()
})
async function expectValidationError(outputStart: number, message: string) {
if (isNextDev) {
await next.fetch('/en/t1')
await retry(() => {
expect(next.cliOutput.slice(outputStart)).toContain(message)
})
} else {
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).toContain(message)
expect(exitCode).toBe(1)
}
expect(next.cliOutput.slice(outputStart)).not.toContain(
'UNEXPECTED_MATCHER_EXECUTION'
)
}
it.each([
[
'static-below',
'unstable_paramMatching',
'may only configure parameters defined at or above its segment',
],
[
'generated-below',
'unstable_generateParamMatching',
'may only configure parameters defined at or above its segment',
],
[
'static-function',
'unstable_paramMatching',
'Expected an object, but received function',
],
[
'generated-object',
'unstable_generateParamMatching',
'must export `unstable_generateParamMatching` as a function',
],
[
'generated-invalid-mode',
'unstable_generateParamMatching',
'Invalid mode for parameter "lang"',
],
[
'static-invalid-mode',
'unstable_paramMatching',
'Invalid mode for parameter "lang"',
],
[
'generated-null',
'unstable_generateParamMatching',
'Expected an object, but received null',
],
])(
'rejects %s in the exporting layout',
async (fixture, exportName, message) => {
const outputStart = next.cliOutput.length
await next.patchFile(
layoutFile,
`${layout}\nexport { ${exportName} } from '../../matchers/${fixture}'\n`
)
await expectValidationError(outputStart, message)
expect(next.cliOutput.slice(outputStart)).toContain(exportName)
}
)
it('rejects private caches with the same request-context error as generateStaticParams', async () => {
const outputStart = next.cliOutput.length
await next.patchFile(
layoutFile,
`${layout}\nexport { unstable_generateParamMatching } from '../../matchers/generated-private-cache'\n`
)
await expectValidationError(
outputStart,
'`"use cache: private"` needs an active request'
)
expect(next.cliOutput.slice(outputStart)).not.toContain(
'Expected a WorkUnitStore'
)
})
it('propagates generator failures without a next.config opt-in', async () => {
const outputStart = next.cliOutput.length
await next.patchFile(
layoutFile,
`${layout}\nexport { unstable_generateParamMatching } from '../../matchers/generated-throws'\n`
)
await expectValidationError(outputStart, 'MATCHER_GENERATOR_FAILURE')
})
})
import { cacheLife, cacheTag } from 'next/cache'
async function readMatchingConfig() {
'use cache'
cacheLife('hours')
cacheTag('matching-config')
return { slug: 'blocking' } as const
}
export async function unstable_generateParamMatching() {
return readMatchingConfig()
}
export function generateStaticParams() {
return [{ slug: 'first' }]
}
export default async function Page({ params }: PageProps<'/cached/[slug]'>) {
return <p id="cached-matcher">Cached matcher: {(await params).slug}</p>
}
export const unstable_paramMatching = { slug: 'not-found' } as const
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return <p id="closed-page">Allowed page</p>
}
import type { ReactNode } from 'react'
// The page replaces lang before the effective route policy is validated.
export const unstable_paramMatching = {
lang: 'fallback',
top: 'blocking',
} as const
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en', top: 't1' }]
}
export default function Page() {
return <p id="composed-matcher">Composed policy</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = {
lang: 'not-found',
slug: 'fallback',
} as const
export function generateStaticParams() {
return [{ lang: 'en', slug: 'allowed' }]
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}) {
return (
<>
<p>Mixed parameter policies</p>
<Suspense fallback={<p>Loading product</p>}>
<Product params={params} />
</Suspense>
</>
)
}
async function Product({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}) {
const { lang, slug } = await params
return <p id="mixed-params">{`${lang}/${slug}`}</p>
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<>
<Link href="/closed/allowed" prefetch={false}>
Closed route
</Link>
<Link href="/mixed/en/allowed" prefetch={false}>
Closed prefix, open suffix
</Link>
<div id="mixed-prefetch">
<LinkAccordion href="/mixed/en/allowed">
Prefetch closed prefix, open suffix
</LinkAccordion>
</div>
</>
)
}
'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: true,
experimental: {
optimisticRouting: true,
// The legacy fixture covers inlining; exercise hint collection without it.
prefetchInlining: false,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import type { PrerenderManifest } from 'next/dist/build'
import {
PrefetchHint,
type FlightRouterState,
} from 'next/dist/shared/lib/app-router-types'
import { createRouterAct } from 'router-act'
describe('param-matching-generators', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
async function getClosedSegments(
browser: Awaited<ReturnType<typeof next.browser>>
) {
// Reconstruct the regression if this private representation changes;
// do not preserve or expose router internals just for this assertion.
return browser.eval((isClosedParamHint) => {
const closedSegments: string[] = []
function visit(tree: FlightRouterState) {
if (((tree[4] ?? 0) & isClosedParamHint) !== 0) {
const segment = tree[0]
closedSegments.push(
typeof segment === 'string' ? segment : `[${segment[0]}]`
)
}
for (const child of Object.values(tree[1])) visit(child)
}
visit(window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree)
return closedSegments
}, PrefetchHint.IsClosedParam)
}
async function hasClosedParamDescendants(
browser: Awaited<ReturnType<typeof next.browser>>
) {
return browser.eval((subtreeHasClosedParamsHint) => {
const tree: FlightRouterState =
window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree
// PrefetchHint.SubtreeHasClosedParams summarizes descendants at the root.
return ((tree[4] ?? 0) & subtreeHasClosedParamsHint) !== 0
}, PrefetchHint.SubtreeHasClosedParams)
}
it('allows public cached configuration in a matching generator', async () => {
for (const slug of ['first', 'novel']) {
const $ = await next.render$(`/cached/${slug}`)
expect($('#cached-matcher').text()).toBe(`Cached matcher: ${slug}`)
}
})
it('validates the effective policy after the page overrides its layout', async () => {
for (const top of ['t1', 'novel']) {
const response = await next.fetch(`/composed/en/${top}`)
expect(response.status).toBe(200)
expect(await response.text()).toContain('Composed policy')
}
expect((await next.fetch('/composed/fr/t1')).status).toBe(404)
})
it.each(['document', 'navigation'])(
'advertises closed parameters for an allowed %s, including in dev',
async (requestKind) => {
const browser = await next.browser(
requestKind === 'document' ? '/closed/allowed' : '/'
)
if (requestKind === 'navigation') {
await browser.elementByCss('a[href="/closed/allowed"]').click()
}
expect(await browser.elementById('closed-page').text()).toBe(
'Allowed page'
)
expect(await getClosedSegments(browser)).toEqual(['[slug]'])
expect(await hasClosedParamDescendants(browser)).toBe(true)
await browser.close()
}
)
it('does not mark open routes as closed', async () => {
const browser = await next.browser('/')
expect(await getClosedSegments(browser)).toEqual([])
expect(await hasClosedParamDescendants(browser)).toBe(false)
await browser.close()
})
it.each(['document', 'navigation'])(
'marks only the closed prefix for a %s to a mixed-policy route',
async (requestKind) => {
const browser = await next.browser(
requestKind === 'document' ? '/mixed/en/allowed' : '/'
)
if (requestKind === 'navigation') {
await browser.elementByCss('a[href="/mixed/en/allowed"]').click()
}
expect(await browser.elementById('mixed-params').text()).toBe(
'en/allowed'
)
expect(await getClosedSegments(browser)).toEqual(['[lang]'])
expect(await hasClosedParamDescendants(browser)).toBe(true)
await browser.close()
}
)
// @force-gate prefetching
it('preserves closed-parameter hints on a prefetched navigation without inlining', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page, { includeAppShellRequests: true })
},
})
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/mixed/en/allowed"]')
.click()
},
{ includes: 'en/allowed' }
)
await act(async () => {
await browser.elementByCss('#mixed-prefetch a').click()
}, 'no-requests')
expect(await browser.elementById('mixed-params').text()).toBe('en/allowed')
expect(await getClosedSegments(browser)).toEqual(['[lang]'])
expect(await hasClosedParamDescendants(browser)).toBe(true)
await browser.close()
})
it('keeps the suffix open without inlining', async () => {
const browser = await next.browser('/mixed/en/novel')
expect(await browser.elementById('mixed-params').text()).toBe('en/novel')
expect(await getClosedSegments(browser)).toEqual(['[lang]'])
expect(await hasClosedParamDescendants(browser)).toBe(true)
await browser.close()
expect((await next.fetch('/mixed/es/allowed')).status).toBe(404)
// Build artifacts are only available locally; the browser and routing
// assertions above also run in dev and against deployments.
if (isNextStart) {
const manifest: PrerenderManifest = await next.readJSON(
'.next/prerender-manifest.json'
)
expect(
manifest.dynamicRoutes['/mixed/[lang]/[slug]'].notFoundParams
).toEqual(['lang'])
}
})
})
export const unstable_paramMatching = { parts: 'blocking' } as const
export default function Page() {
return <p>Sidebar</p>
}
export default function Page() {
return <p>Catch-all page</p>
}
export default function Page() {
return <p>Single-segment page</p>
}
import type { ReactNode } from 'react'
export default function Root({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<html>
<body>
{children}
{sidebar}
</body>
</html>
)
}
export default function Page() {
return <p>Index</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = { cacheComponents: true }
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// This policy deliberately fails validation, so the app cannot be deployed.
// @force-gate !deploy
describe('param-matching-parallel-catchall', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('rejects a catch-all policy for a parameter outside the matched pathname', async () => {
if (isNextDev) {
await next.start()
expect((await next.fetch('/one')).status).toBe(500)
} else {
const { exitCode } = await next.build()
expect(exitCode).toBe(1)
}
// "parts" is in scope for the sidebar's export, but /[slug] supplies its
// value from the matched pathname rather than having a [parts] parameter.
await retry(() => {
expect(next.cliOutput).toContain(
'Invalid parameter "parts" in `unstable_paramMatching` for "/[slug]". Parameter matching may only configure dynamic parameters in this route.'
)
})
expect(next.cliOutput).not.toContain(
'may only configure parameters defined at or above its segment'
)
})
})
export const unstable_paramMatching = { id: 'not-found' } as const
export function generateStaticParams() {
return [{ category: 'shoes', id: 'one' }]
}
export default function Page() {
return <p>Must not implicitly close category</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = { category: 'not-found' } as const
export function generateStaticParams() {
return [{ category: 'shoes' }]
}
export default function Page() {
return <p>Must not implicitly close lang</p>
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'node:path'
import { retry } from 'next-test-utils'
// Invalid exports must fail before a deployment can be produced.
// @force-gate !deploy
describe.each([
['root', '/en/shoes', 'lang', 'category'],
['middle', '/en/shoes/one', 'category', 'id'],
])('param-matching-prefix: %s', (fixture, url, missing, closed) => {
const { next, isNextDev } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'fixtures', fixture)),
'next.config.ts': new FileRef(join(__dirname, 'next.config.ts')),
},
skipStart: true,
})
it('requires an explicit not-found policy for every preceding parameter', async () => {
const message = `Parameter "${missing}" must explicitly configure "not-found" before parameter "${closed}"`
if (isNextDev) {
await next.start()
expect((await next.fetch(url)).status).toBe(500)
await retry(() => expect(next.cliOutput).toContain(message))
} else {
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).toContain(message)
expect(exitCode).toBe(1)
}
})
})
import { Suspense } from 'react'
import { lang } from 'next/root-params'
import { cacheTag } from 'next/cache'
async function data(key: string) {
const response = await fetch(
`${process.env.TEST_DATA_SERVICE_URL}?key=${key}`,
{
cache: 'no-store',
}
)
return response.text()
}
async function cachedLanguage() {
'use cache'
cacheTag('isolated-root-shell')
// The data service holds this fill until the top-level consumer has joined.
await data('joined-inner-started')
return (await lang()).toUpperCase()
}
async function NestedConsumer() {
'use cache'
cacheTag('isolated-root-shell')
return <p id="joined-nested">{await cachedLanguage()}</p>
}
async function waitForNestedFill() {
'use cache'
cacheTag('isolated-root-shell')
await data('joined-top-level-ready')
}
async function releaseNestedFill() {
'use cache'
cacheTag('isolated-root-shell')
await data('joined-top-level-called')
}
async function TopLevelConsumer() {
await waitForNestedFill()
const language = cachedLanguage()
await releaseNestedFill()
return <p id="joined-top-level">{await language}</p>
}
export default function Page() {
return (
<>
<Suspense fallback={<p id="joined-nested-pending">Loading nested</p>}>
<NestedConsumer />
</Suspense>
<Suspense
fallback={<p id="joined-top-level-pending">Loading top level</p>}
>
<TopLevelConsumer />
</Suspense>
</>
)
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = { lang: 'fallback' }
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<h1>Language-independent shell</h1>
{children}
</body>
</html>
)
}
import { Suspense } from 'react'
import { lang } from 'next/root-params'
import { cacheTag } from 'next/cache'
async function data(key: string) {
const response = await fetch(
`${process.env.TEST_DATA_SERVICE_URL}?key=${key}`,
{
cache: 'no-store',
}
)
return response.text()
}
async function sharedContent() {
'use cache'
cacheTag('isolated-root-shell')
return data('shared')
}
async function cachedLanguage() {
'use cache'
cacheTag('isolated-root-shell')
await data('before-language')
const language = lang().then((value) => value.toUpperCase())
// Signal that the root promise was consumed, not just created. The test data
// service keeps the independent fill pending until this access has happened.
await data('language-read')
return language
}
async function RootDependent() {
'use cache'
// Start the independent fill inside the cache that will be cancelled. It
// must survive that cancellation for a different consumer to use its result.
const shared = sharedContent()
const language = await cachedLanguage()
return <p id="localized">{language + ':' + (await shared)}</p>
}
async function IndependentConsumer() {
'use cache'
await data('independent-consumer')
return <p id="independent">{await sharedContent()}</p>
}
export default function Page() {
return (
<>
<Suspense fallback={<p id="localized-pending">Loading language</p>}>
<RootDependent />
</Suspense>
<Suspense
fallback={<p id="independent-pending">Loading shared content</p>}
>
<IndependentConsumer />
</Suspense>
</>
)
}
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('isolated-root-shell', { expire: 0 })
return new Response(null, { status: 204 })
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { findPort } from 'next-test-utils'
import { createTestDataServer } from 'test-data-service/writer'
import { load } from 'cheerio'
import { PrefetchHint } from 'next/src/shared/lib/app-router-types'
import { UNEXPECTED_CACHE_MISS_MESSAGE } from 'next/src/server/use-cache/use-cache-errors'
// This inspects local build artifacts and uses a process-local data service. The
// existing param-matching-root-params suite covers deployed root fallbacks.
// @force-gate start
describe('param-matching-root-cache-isolation', () => {
let server: ReturnType<typeof createTestDataServer>
const requests: string[] = []
let controlRequests = false
let controlJoinedRequests = false
const joinedRequests: string[] = []
const joinedPending = new Map<string, () => void>()
let nestedFillReleased = false
let joinedAttempts = 0
let buildShell: string
let buildMetadata: string
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
beforeAll(async () => {
const port = await findPort()
const pending = new Map<string, () => void>()
let languageRead = false
server = createTestDataServer((key, response) => {
if (controlJoinedRequests && key.startsWith('joined-')) {
joinedRequests.push(key)
if (nestedFillReleased) {
response.resolve()
} else if (key === 'joined-inner-started') {
joinedPending.set(key, () => response.resolve())
joinedPending.get('joined-top-level-ready')?.()
} else if (key === 'joined-top-level-ready') {
if (joinedPending.has('joined-inner-started')) {
response.resolve()
} else {
joinedPending.set(key, () => response.resolve())
}
} else if (key === 'joined-top-level-called') {
nestedFillReleased = true
response.resolve()
joinedPending.get('joined-inner-started')?.()
} else {
throw new Error(`Unexpected joined-cache request: ${key}`)
}
return
}
if (!controlRequests) {
response.resolve(key === 'shared' ? 'shared content' : key)
return
}
requests.push(key)
if (key === 'language-read') {
languageRead = true
response.resolve()
// The root-dependent cache is now cancelled. Let the other consumer
// join the independent fill and let that fill finish.
pending.get('independent-consumer')?.()
pending.get('shared')?.()
} else if (languageRead) {
response.resolve(key === 'shared' ? 'shared content' : key)
} else if (key === 'shared') {
pending.set(key, () => response.resolve('shared content'))
pending.get('before-language')?.()
} else if (key === 'before-language' && pending.has('shared')) {
response.resolve()
} else {
pending.set(key, () => response.resolve())
}
})
server.listen(port)
next.env.TEST_DATA_SERVICE_URL = `http://localhost:${port}`
await next.start()
// ISR replaces these files. Snapshot the build's measurements before any
// request so the hint assertion doesn't depend on test ordering.
buildShell = await next.readFile('.next/server/app/[lang].html')
buildMetadata = await next.readFile('.next/server/app/[lang].meta')
})
afterAll(() => {
server?.close()
})
it('does not cancel an independent pending fill when a nested cache reads an unknown root', async () => {
controlRequests = true
const revalidation = await next.fetch('/revalidate', { method: 'POST' })
expect(revalidation.status).toBe(204)
// A novel language selects the expired generic shell. It must now fill
// caches from scratch, without the RDC used to seed the build-time shell.
const $ = await next.render$('/fr')
expect(requests).toContain('language-read')
expect(requests.filter((key) => key === 'shared')).toHaveLength(1)
expect($('#independent').text()).toBe('shared content')
expect($('#independent').closest('[hidden]').length).toBe(0)
expect($('#independent-pending').length).toBe(0)
expect($('#localized').text()).toBe('FR:shared content')
expect($('#localized').closest('[hidden]').length).toBe(1)
expect($('#localized-pending').length).toBe(1)
const $other = await next.render$('/de')
expect($other('#independent').text()).toBe('shared content')
expect($other('#independent').closest('[hidden]').length).toBe(0)
expect($other('#localized').text()).toBe('DE:shared content')
expect(requests.filter((key) => key === 'shared')).toHaveLength(1)
})
it('keeps the static-prefetch hint when only the fallback root prevents a complete shell', async () => {
const $ = load(buildShell)
expect($('#localized').length).toBe(0)
const meta = JSON.parse(buildMetadata)
expect(
(meta.prefetchHints?.hints ?? 0) &
PrefetchHint.ShouldAttemptStaticPrefetch
).toBe(PrefetchHint.ShouldAttemptStaticPrefetch)
})
it('records the omission reason when a top-level consumer joins a nested cache fill', async () => {
joinedRequests.length = 0
joinedPending.clear()
nestedFillReleased = false
// A retry must use the generic shell too, not a concrete page produced by
// the previous attempt's background upgrade.
const language = `fr-${++joinedAttempts}`
controlJoinedRequests = true
const revalidation = await next.fetch('/revalidate', { method: 'POST' })
expect(revalidation.status).toBe(204)
const logStart = next.cliOutput.length
const $ = await next.render$(`/${language}/joined`)
expect(joinedRequests.slice(0, 2)).toEqual(
expect.arrayContaining(['joined-inner-started', 'joined-top-level-ready'])
)
expect(joinedRequests[2]).toBe('joined-top-level-called')
expect($('#joined-nested').text()).toBe(language.toUpperCase())
expect($('#joined-top-level').text()).toBe(language.toUpperCase())
expect($('#joined-nested-pending').length).toBe(1)
expect($('#joined-top-level-pending').length).toBe(1)
expect($('#joined-nested').closest('[hidden]').length).toBe(1)
expect($('#joined-top-level').closest('[hidden]').length).toBe(1)
// The nested leader has no RDC. Its top-level joiner must record the hole
// so the final prerender knows this is fallback data, not an unexplained miss.
expect(next.cliOutput.slice(logStart)).not.toContain(
UNEXPECTED_CACHE_MISS_MESSAGE
)
})
})
import { writeFile } from 'node:fs/promises'
export default {
name: 'capture-param-matching-query-contract',
async onBuildComplete({ outputs, routing }) {
// Capture only the public query-key contract, not bypass tokens or build
// paths. The behavioral tests also run without access to these artifacts.
await writeFile(
'query-contract.json',
JSON.stringify({
prerenders: outputs.prerenders.map(
({ pathname, config, fallback }) => ({
pathname,
allowQuery: config.allowQuery,
hasFallback: fallback?.filePath !== undefined,
})
),
routes: routing.dynamicRoutes.map(({ source, destination }) => ({
source,
destination,
})),
})
)
},
}
import type { ReactNode } from 'react'
import Link from 'next/link'
export async function unstable_generateParamMatching() {
return { lang: 'fallback' } as const
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<h1>Language-independent shell</h1>
<nav>
<Link href="/en" prefetch={false}>
English
</Link>
<Link href="/fr" prefetch={false}>
French
</Link>
<Link href="/de" prefetch={false}>
German
</Link>
</nav>
{children}
</body>
</html>
)
}
import { Suspense } from 'react'
import { lang } from 'next/root-params'
import { cacheTag } from 'next/cache'
import { randomUUID } from 'node:crypto'
async function ShellVersion() {
'use cache'
cacheTag('root-fallback-shell')
return <p id="shell-version">{randomUUID()}</p>
}
async function cachedLanguage() {
'use cache'
return (await lang()).toUpperCase()
}
async function NestedLanguage() {
'use cache'
return <p id="nested-lang">{'nested:' + (await cachedLanguage())}</p>
}
async function DirectLanguage() {
return <p id="direct-lang">{await lang()}</p>
}
async function CachedBoundary() {
'use cache'
return (
<>
<p id="cache-prefix">Cached language UI</p>
<Suspense fallback={<p id="inner-pending">language pending</p>}>
<DirectLanguage />
</Suspense>
</>
)
}
export default function Page() {
return (
<>
<ShellVersion />
<Suspense fallback={<p id="nested-pending">nested language pending</p>}>
<NestedLanguage />
</Suspense>
<Suspense fallback={<p id="outer-pending">cached UI pending</p>}>
<CachedBoundary />
</Suspense>
</>
)
}
import { Suspense } from 'react'
import { lang } from 'next/root-params'
async function CachedLanguage() {
'use cache'
const value = await lang()
return <p id="cached-lang">{'locale:' + value.toUpperCase()}</p>
}
async function DirectLanguage() {
const value = await lang()
return (
<p id="direct-lang" data-language={value}>
{value}
</p>
)
}
export default function Page() {
return (
<>
<Suspense fallback={<p>cached language pending</p>}>
<CachedLanguage />
</Suspense>
<Suspense fallback={<p>direct language pending</p>}>
<DirectLanguage />
</Suspense>
</>
)
}
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('root-fallback-shell', { expire: 0 })
return new Response(null, { status: 204 })
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Local artifact capture must not replace the real adapter in deploy tests.
adapterPath:
process.env.CAPTURE_QUERY_CONTRACT === '1'
? require.resolve('./adapter.mjs')
: undefined,
}
export default nextConfig
import { isNextStart, nextTestSetup } from 'e2e-utils'
import { gate } from 'next-test-utils'
describe('param-matching-root-params', () => {
const { next } = nextTestSetup({
files: __dirname,
env: { CAPTURE_QUERY_CONTRACT: isNextStart ? '1' : '' },
})
it('resolves both cached and uncached reads for a build-time example', async () => {
const $ = await next.render$('/en')
expect($('#direct-lang').text()).toBe('en')
expect($('#cached-lang').text()).toBe('locale:EN')
})
it.each(['fr', 'de'])(
'resolves cached computations for novel root %s',
async (language) => {
const $ = await next.render$(`/${language}`)
expect($('#direct-lang').text()).toBe(language)
expect($('#cached-lang').text()).toBe(`locale:${language.toUpperCase()}`)
}
)
it('does not retain placeholder-derived content or another root in the cache', async () => {
for (const language of ['it', 'nl', 'it', 'en']) {
const $ = await next.render$(`/${language}`)
expect($('#direct-lang').text()).toBe(language)
expect($('#cached-lang').text()).toBe(`locale:${language.toUpperCase()}`)
}
})
it('agrees after navigation across roots and after refresh', async () => {
const browser = await next.browser('/en')
await browser.elementByCss('a[href="/fr"]').click()
expect(
await browser.elementByCss('#direct-lang[data-language="fr"]').text()
).toBe('fr')
expect(await browser.elementById('cached-lang').text()).toBe('locale:FR')
await browser.refresh()
expect(await browser.elementById('cached-lang').text()).toBe('locale:FR')
await browser.elementByCss('a[href="/de"]').click()
expect(
await browser.elementByCss('#direct-lang[data-language="de"]').text()
).toBe('de')
expect(await browser.elementById('cached-lang').text()).toBe('locale:DE')
})
it('propagates unresolved root reads through nested cache fills', async () => {
for (const language of ['en', 'fr', 'de', 'fr']) {
const $ = await next.render$(`/${language}/nested`)
expect($('#nested-lang').text()).toBe(`nested:${language.toUpperCase()}`)
}
})
// Dev renders requests dynamically rather than serving and regenerating
// fallback shells. This exercises ordinary production revalidation.
// @force-gate !dev
it('keeps novel roots isolated after fallback invalidation', async () => {
const $before = await next.render$('/en/nested')
const originalVersion = $before('#shell-version').text()
expect(originalVersion).not.toBe('')
const response = await next.fetch('/revalidate', { method: 'POST' })
expect(response.status).toBe(204)
// Expiring the tagged data forces a fresh fill for a novel language,
// rather than serving the shell produced at build time.
const $ = await next.render$('/it/nested')
const regeneratedVersion = $('#shell-version').text()
expect(regeneratedVersion).not.toBe('')
expect(regeneratedVersion).not.toBe(originalVersion)
expect($('#shell-version').closest('[hidden]').length).toBe(0)
expect($('#nested-lang').text()).toBe('nested:IT')
expect($('#direct-lang').text()).toBe('it')
const hasGenericFallbackShell = await gate(
(conditions) => !conditions.deploy
)
if (hasGenericFallbackShell) {
// Locally, unknown roots share the generic fallback shell. Deployment
// adapters may vary the shell on the concrete root query key instead.
expect($('#nested-pending').length).toBe(1)
expect($('#outer-pending').length).toBe(1)
expect($('#nested-lang').closest('[hidden]').length).toBe(1)
expect($('#cache-prefix').closest('[hidden]').length).toBe(1)
}
// A different root must never reuse root-dependent cached content. Local
// production also guarantees that both roots share the generic shell;
// deployment adapters may generate root-specific static HTML instead.
const $other = await next.render$('/nl/nested')
expect($other('#shell-version').text()).not.toBe('')
if (hasGenericFallbackShell) {
expect($other('#shell-version').text()).toBe(regeneratedVersion)
}
expect($other('#nested-lang').text()).toBe('nested:NL')
expect($other('#direct-lang').text()).toBe('nl')
const $again = await next.render$('/it/nested')
expect($again('#shell-version').text()).not.toBe('')
expect($again('#nested-lang').text()).toBe('nested:IT')
expect($again('#direct-lang').text()).toBe('it')
})
// Inspect the real build's adapter output locally. The behavioral tests above
// also run in deploy mode, where these build artifacts are not available.
// @force-gate start
it('emits a servable root fallback with the exact query keys routing forwards', async () => {
const contract = await next.readJSON('query-contract.json')
const route = contract.routes.find(({ source }) => source === '/[lang]')
expect(route).toBeDefined()
const forwardedKeys = Array.from(
new URL(route.destination, 'https://example.test').searchParams.keys()
)
expect(forwardedKeys).toEqual(['nxtPlang'])
const output = contract.prerenders.find(
({ pathname }) => pathname === '/[lang]'
)
expect(output).toMatchObject({
hasFallback: true,
allowQuery: forwardedKeys,
})
const dataOutput = contract.prerenders.find(
({ pathname }) => pathname === '/[lang].rsc'
)
expect(dataOutput).toMatchObject({ allowQuery: forwardedKeys })
const segmentOutputs = contract.prerenders.filter(({ pathname }) =>
pathname.startsWith('/[lang].segments/')
)
expect(segmentOutputs.length).toBeGreaterThan(0)
for (const segmentOutput of segmentOutputs) {
expect(segmentOutput.allowQuery).toEqual(forwardedKeys)
}
})
})
# Parameter matching regression coverage
These suites test the contract across build, request handling, caches, client
navigation, and deployment. Emitting the expected matcher or returning HTTP 200
is not sufficient: an admitted request must reach the right page with the right
params, and a rejected request must not render that page's nested not-found UI.
The new regression assertions are intentionally not gated on the presence of a
bug. Keep the tests unchanged when fixing the implementation. Mode gates only
exclude unavailable capabilities, such as prefetching in development or reading
local build artifacts from a deployment.
## Request and deployment boundaries
| Contract | Fixture and assertions |
| --- | --- |
| A closed prefix does not close its open suffix | This suite: `lang: not-found`, `top: blocking`, `bottom: fallback`; seeded and on-demand-only pages; both `en` and `es`; cold and repeated document requests |
| Dynamic suffixes are not captured in prerenders | This suite: different bottom values beneath the same generated or novel top; [runtime suite](../param-matching-runtime/param-matching-runtime.test.ts): compare shell generations across top and bottom changes |
| Parameter encoding survives routing and cache lookup | This suite: multi-part catch-all with spaces and a literal percent sign; preserve existing URI-encoded server params with and without matching configuration |
| Routing rejection applies to every request form | This suite: documents, RSC, route-tree prefetches, unmatched static segments, and nested not-found boundaries |
| Client route discovery preserves admission | This suite: prefetch a 404 before navigating to an allowed open suffix; prefetch an allowed suffix before navigating to a rejected prefix; compare with refresh |
| Cache invalidation does not change route admission | This suite: `revalidatePath` for fully closed and partially closed routes, including runtime-generated outputs and invalid URLs; route-pattern invalidation regenerates a shared dynamic-tail shell without capturing either request's dynamic value |
| Expected misses are not internal server errors | This suite: inspect local server output after a routing 404 |
| Blocking means concrete generation before the response | [Runtime suite](../param-matching-runtime/param-matching-runtime.test.ts): seeded and seedless routes, different cold keys, concurrent cold requests, and warm requests |
| Fallback and upgrade are distinct operations | Runtime suite: shared first-visitor HTML, concrete response params, subsequent upgrade when Partial Prefetching is enabled, and unchanged shared shell when it is disabled |
| An unresolved root must not contaminate cached computations | [Root-param suite](../param-matching-root-params/param-matching-root-params.test.ts): cached and uncached root reads for seeded and novel languages; repeated visits, cross-root navigation, and refresh |
| Deployment cache-key names agree with routing | Root-param suite: every `allowQuery` key on the root fallback is actually forwarded by the corresponding routing destination |
| Non-URL tree depth does not change policy order | [Parallel/group suite](../../../production/app-dir/param-matching-route-groups/param-matching-route-groups.test.ts): identical URL policies with aligned branches, a group in the named slot, and a group in children; static and generated exports |
The root tests describe the currently accepted `lang: fallback` configuration.
If root fallbacks are deliberately prohibited instead, that is an API decision,
not a reason to weaken assertions about corrupted cached content.
## Existing compiler and validation coverage
These tests complement, rather than replace, the existing suites:
- [Main API suite](../generate-prerender-matching/generate-prerender-matching.test.ts): inheritance and explicit overrides, uniform policies, inferred policies, holes, dynamic tails, emitted matchers, root/catch-all/optional-catch-all routes, parallel agreement, typegen key visibility, feature/Cache Components requirements, export restrictions, empty-shell validation, and anonymized dev validation.
- [Export validation](../param-matching-exports/param-matching-exports.test.ts): static versus generated exports, invalid return values, parameter visibility, and checking the feature flag before executing a generator.
- [Not-found coherence](../../../production/app-dir/param-matching-not-found/param-matching-not-found.test.ts): missing sibling/ancestor/parallel declarations, route groups, generated declarations, inherited overrides, explicit disagreement, and independent parameters with the same name.
- [Parallel inheritance](../../../production/app-dir/param-matching-parallel-inheritance/param-matching-parallel-inheritance.test.ts): preserve each branch's inherited policy while combining parallel branches.
- [Unseeded prefixes](../../../production/app-dir/param-matching-unseeded-prefix/param-matching-unseeded-prefix.test.ts): explicit policies extend the prerenderable prefix; empty/nonempty shell inference; unconfigured tails stay dynamic.
- [Inferred root behavior](../../../production/app-dir/param-matching-root-fallback/param-matching-root-fallback.test.ts): inferred root blocking and policies beneath a known root.
- [Closed client routes](../segment-cache-closed-params/segment-cache-closed-params.test.ts) and [legacy dynamicParams](../segment-cache-dynamic-params/segment-cache-dynamic-params.test.ts): client-cache admission and the non-Cache Components comparison.
## Verification matrix
Run the runtime and routing suites with both bundlers and with Partial
Prefetching enabled and disabled. Their default configuration enables it;
`__NEXT_TEST_AXIS=A` disables it. Assertions about explicit policy do not change
between the two configurations. The upgrade assertions account separately for
the existing Partial-Prefetching-only upgrade feature.
```sh
pnpm test-start-turbo test/e2e/app-dir/param-matching-runtime test/e2e/app-dir/param-matching-routing
__NEXT_TEST_AXIS=A pnpm test-start-turbo test/e2e/app-dir/param-matching-runtime test/e2e/app-dir/param-matching-routing
pnpm test-start-webpack test/e2e/app-dir/param-matching-runtime test/e2e/app-dir/param-matching-routing
__NEXT_TEST_AXIS=A pnpm test-start-webpack test/e2e/app-dir/param-matching-runtime test/e2e/app-dir/param-matching-routing
pnpm test-start-turbo test/e2e/app-dir/param-matching-root-params test/production/app-dir/param-matching-route-groups
pnpm test-start-webpack test/e2e/app-dir/param-matching-root-params test/production/app-dir/param-matching-route-groups
pnpm test-dev-turbo test/e2e/app-dir/generate-prerender-matching test/e2e/app-dir/param-matching-exports test/e2e/app-dir/param-matching-root-params test/e2e/app-dir/param-matching-routing
pnpm test-dev-webpack test/e2e/app-dir/generate-prerender-matching test/e2e/app-dir/param-matching-exports test/e2e/app-dir/param-matching-root-params test/e2e/app-dir/param-matching-routing
```
Run the existing production suites above as well. They cover configuration and
validation combinations that the request fixtures intentionally keep simple.
## Deployment is a separate acceptance check
The routing and root-param HTTP/browser assertions also support deployment
mode. The query-contract assertion is local-only and must not substitute for a
real adapter deployment:
```sh
NEXT_ENABLE_ADAPTER=1 pnpm test-deploy-turbo test/e2e/app-dir/param-matching-routing test/e2e/app-dir/param-matching-root-params
NEXT_ENABLE_ADAPTER=1 pnpm test-deploy-webpack test/e2e/app-dir/param-matching-routing test/e2e/app-dir/param-matching-root-params
```
Use the configured deployment-test credentials. Do not embed a local adapter
checkout, substitute a mocked function launcher, or change metadata in a test
adapter to make these requests pass.
A local `next start` pass does not establish adapter compatibility. Before
declaring the closed-prefix deployment issue fixed, confirm the deployment
actually uses grouped functions and exercises the cold open suffixes in this
fixture. Function grouping and routing-level rejection without function/ISR
invocation require deployment evidence; this suite does not infer either from
HTTP status alone. Revalidation and cold requests must work on that deployment
with the unchanged adapter; captured routing regexes alone cannot prove this.
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export { CatalogPage as default } from '../../../../../catalog-page'
export const unstable_paramMatching = { slug: 'not-found' } as const
export function generateStaticParams() {
return [
{ slug: 'known' },
{ slug: 'hello world' },
{ slug: '100%' },
{ slug: 'literal%20value' },
]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}) {
const { lang, slug } = await params
return (
<main id="closed-page">
<p id="params">{`${lang}/${slug}`}</p>
<p id="generation">{performance.now().toFixed(5)}</p>
</main>
)
}
import { Suspense } from 'react'
export const unstable_paramMatching = { parts: 'blocking' } as const
async function Content({
params,
}: {
params: Promise<{ lang: string; parts: string[] }>
}) {
const { lang, parts } = await params
return <p id="params">{`${lang}/${parts.join('/')}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; parts: string[] }>
}) {
return (
<main id="docs-page">
<h1>Documentation</h1>
<Suspense fallback={<p>Loading documentation</p>}>
<Content params={params} />
</Suspense>
</main>
)
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'dynamic',
} as const
export function generateStaticParams() {
return [{ top: 't1' }]
}
export { CatalogPage as default } from '../../../../catalog-page'
import type { ReactNode } from 'react'
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'es' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <section id="language-layout">{children}</section>
}
export default function NotFound() {
return <p id="nested-not-found">Nested not found</p>
}
export async function unstable_generateParamMatching() {
return { top: 'blocking', bottom: 'fallback' } as const
}
export { CatalogPage as default } from '../../../../../catalog-page'
import { Suspense } from 'react'
type Params = Promise<{ lang: string; top: string; bottom: string }>
async function Content({ params }: { params: Params }) {
const { lang, top, bottom } = await params
return <p id="params">{`${lang}/${top}/${bottom}`}</p>
}
export function CatalogPage({ params }: { params: Params }) {
return (
<main id="catalog-page">
<h1>Catalog</h1>
<p id="generation">{performance.now().toFixed(5)}</p>
<Suspense fallback={<p id="pending">Loading catalog</p>}>
<Content params={params} />
</Suspense>
</main>
)
}
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 { Suspense } from 'react'
// Unconfigured control for the closed-prefix catch-all route. Encoding must
// survive regardless of whether an explicit matching policy is present.
async function Content({ params }: { params: Promise<{ parts: string[] }> }) {
const { parts } = await params
return <p id="params">{parts.join('/')}</p>
}
export default function Page({
params,
}: {
params: Promise<{ parts: string[] }>
}) {
return (
<main>
<h1>Unconfigured documentation</h1>
<Suspense fallback={<p>Loading documentation</p>}>
<Content params={params} />
</Suspense>
</main>
)
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Closed prefixes with open suffixes</h1>
<LinkAccordion href="/en/catalog/nav-top/items/nav-bottom">
Allowed catalog
</LinkAccordion>
<LinkAccordion href="/fr/catalog/nav-top/items/nav-bottom">
Rejected catalog
</LinkAccordion>
<LinkAccordion href="/es/on-demand/nav-top/items/nav-bottom">
Unseeded catalog
</LinkAccordion>
<Link
href="/fr/catalog/nav-top/items/nav-bottom"
prefetch={false}
id="navigate-rejected"
>
Rejected without prefetch
</Link>
</main>
)
}
import { revalidatePath } from 'next/cache'
export async function POST(request: Request) {
const { pathname, type } = await request.json()
revalidatePath(pathname, type)
return Response.json({ revalidated: true })
}
'use client'
import Link from 'next/link'
import { useState, type ReactNode } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: ReactNode
}) {
const [visible, setVisible] = useState(false)
return (
<div>
<input
type="checkbox"
checked={visible}
onChange={() => setVisible(!visible)}
data-link-accordion={href}
/>
{visible ? <Link href={href}>{children}</Link> : children}
</div>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: process.env.__NEXT_TEST_AXIS !== 'A',
experimental: { optimisticRouting: true },
async rewrites() {
return [
{
source: '/en/closed/alias',
destination: '/en/closed/known',
},
{
source: '/en/closed/encoded-alias',
destination: '/en/closed/hello%20world',
},
{
source: '/en/closed/percent-alias',
destination: '/en/closed/100%25',
},
{
source: '/en/closed/missing-alias',
destination: '/en/closed/unlisted',
},
{
source: '/fr/catalog/alias/items/:bottom',
destination: '/en/catalog/novel-top/items/:bottom',
},
{
source: '/en/catalog/blocked-alias/items/:bottom',
destination: '/fr/catalog/novel-top/items/:bottom',
},
]
},
}
export default nextConfig
import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import { gate, retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
describe('param-matching-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function render(pathname: string, params: string) {
const res = await next.fetch(pathname)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#params').text()).toBe(params)
expect($('#root-not-found, #nested-not-found').length).toBe(0)
return $('#generation').text()
}
it.each([
['/en/catalog/t1/items/b1', 'en/t1/b1'],
['/es/catalog/t1/items/b1', 'es/t1/b1'],
['/en/catalog/t1/items/novel-bottom', 'en/t1/novel-bottom'],
['/en/catalog/novel-top/items/novel-bottom', 'en/novel-top/novel-bottom'],
['/es/catalog/novel-top/items/novel-bottom', 'es/novel-top/novel-bottom'],
['/en/on-demand/novel-top/items/novel-bottom', 'en/novel-top/novel-bottom'],
['/es/on-demand/other-top/items/other-bottom', 'es/other-top/other-bottom'],
['/en/dynamic/t1/first', 'en/t1/first'],
['/en/dynamic/t1/second', 'en/t1/second'],
['/es/dynamic/new-top/anything', 'es/new-top/anything'],
['/en/docs/getting-started/install', 'en/getting-started/install'],
// Server params currently expose URI-encoded values, as also asserted by
// prerender-encoding. Matching configuration must not change that contract.
['/es/docs/space%20here/install', 'es/space%20here/install'],
['/es/docs/space%20here/100%25', 'es/space%20here/100%25'],
['/open/docs/space%20here/install', 'space%20here/install'],
['/open/docs/space%20here/100%25', 'space%20here/100%25'],
])(
'serves an admitted path through its real handler: %s',
async (pathname, params) => {
await render(pathname, params)
await render(pathname, params)
}
)
it('keeps simultaneous requests to different closed prefixes isolated', async () => {
await Promise.all([
render('/en/on-demand/concurrent/items/one', 'en/concurrent/one'),
render('/es/on-demand/concurrent/items/one', 'es/concurrent/one'),
render('/en/on-demand/concurrent/items/two', 'en/concurrent/two'),
])
})
describe('resolved matching paths', () => {
it.each([
['/en/closed/hello%20world', 'en/hello%20world'],
['/en/closed/100%25', 'en/100%25'],
['/en/closed/literal%2520value', 'en/literal%2520value'],
['/en/closed/alias', 'en/known'],
['/en/closed/encoded-alias', 'en/hello%20world'],
['/en/closed/percent-alias', 'en/100%25'],
[
'/fr/catalog/alias/items/rewritten-bottom',
'en/novel-top/rewritten-bottom',
],
])('admits an allowed resolved path: %s', async (pathname, params) => {
await render(pathname, params)
})
it.each([
'/en/closed/not%20generated',
// Decoding twice would turn this different value into "hello world".
'/en/closed/hello%2520world',
'/en/closed/missing-alias',
'/en/catalog/blocked-alias/items/rewritten-bottom',
])('rejects an unlisted resolved path: %s', async (pathname) => {
const res = await next.fetch(pathname)
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#root-not-found').text()).toBe('Route not found')
expect($('#closed-page, #catalog-page').length).toBe(0)
})
})
it.each([
'/fr/catalog/t1/items/b1',
'/fr/catalog/new-top/items/new-bottom',
'/fr/on-demand/new-top/items/new-bottom',
'/fr/dynamic/new-top/anything',
'/fr/docs/getting-started/install',
'/en/closed/unlisted',
'/en/catalog/t1/wrong-static-segment/b1',
])(
'rejects %s without rendering the matched page or its nested 404',
async (pathname) => {
const res = await next.fetch(pathname, { redirect: 'manual' })
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#root-not-found').text()).toBe('Route not found')
expect(
$(
'#language-layout, #catalog-page, #closed-page, #docs-page, #nested-not-found'
).length
).toBe(0)
}
)
it.each(['catalog', 'on-demand'])(
'admits only the closed prefix for %s RSC and route discovery requests',
async (route) => {
for (const headers of [
{ RSC: '1' },
{
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/_tree',
},
]) {
const admitted = await next.fetch(
`/en/${route}/rsc-top/items/rsc-bottom`,
{ headers }
)
expect(admitted.status).toBe(200)
expect(admitted.headers.get('content-type')).toContain(
'text/x-component'
)
await admitted.text()
const rejected = await next.fetch(
`/fr/${route}/rsc-top/items/rsc-bottom`,
{ headers }
)
expect(rejected.status).toBe(404)
await rejected.text()
}
}
)
// @force-gate start
it('handles an expected matcher miss without a cache-generation invariant error', async () => {
const outputStart = next.cliOutput.length
const res = await next.fetch('/fr/catalog/missing/items/missing')
await res.text()
expect(res.status).toBe(404)
expect(next.cliOutput.slice(outputStart)).not.toMatch(/invariant:|Error:/i)
})
// @force-gate prod
describe('revalidation', () => {
it.each([
['/en/closed/known', 'en/known'],
['/es/catalog/t1/items/b1', 'es/t1/b1'],
[
'/en/catalog/revalidation-top/items/revalidation-bottom',
'en/revalidation-top/revalidation-bottom',
],
[
'/es/on-demand/revalidation-top/items/revalidation-bottom',
'es/revalidation-top/revalidation-bottom',
],
])(
'revalidates a seeded or runtime-generated output without changing route admission: %s',
async (pathname, params) => {
const before = await render(pathname, params)
expect(before).not.toBe('')
expect(await render(pathname, params)).toBe(before)
const res = await next.fetch('/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname }),
})
expect(res.status).toBe(200)
await retry(async () => {
expect(await render(pathname, params)).not.toBe(before)
})
const rejected = await next.fetch('/fr/closed/known')
expect(rejected.status).toBe(404)
await rejected.text()
}
)
it('regenerates a shared dynamic-tail shell without capturing a request value', async () => {
const first = '/en/dynamic/revalidation-top/first'
const second = '/en/dynamic/revalidation-top/second'
const isDeploy = await gate((conditions) => conditions.deploy)
const deploymentStabilizationTimeout = 10_000
// Vercel may treat a new or just-regenerated shell as already stale,
// replacing it on the next visits before its cache entry stabilizes.
// This deploy-only allowance retries both suffixes together before and
// after invalidation. It is separate from the cache-key/capture contract:
// every attempt still verifies distinct params and a shared shell, and
// this does not claim that cold-cache deduplication or freshness is fixed.
async function readStableDeploymentGeneration(
previousGeneration?: string
) {
const result = await retry(async () => {
let firstGeneration: string
let secondGeneration: string
try {
firstGeneration = await render(first, 'en/revalidation-top/first')
secondGeneration = await render(
second,
'en/revalidation-top/second'
)
} catch (error) {
// Admission and param-isolation failures are never retryable.
// Return them through retry, then rethrow immediately below.
return { error }
}
expect(firstGeneration).not.toBe('')
expect(secondGeneration).toBe(firstGeneration)
if (previousGeneration !== undefined) {
expect(firstGeneration).not.toBe(previousGeneration)
}
return { generation: firstGeneration }
}, deploymentStabilizationTimeout)
if ('error' in result) {
throw result.error
}
return result.generation
}
let before: string
if (isDeploy) {
before = await readStableDeploymentGeneration()
} else {
before = await render(first, 'en/revalidation-top/first')
expect(before).not.toBe('')
expect(await render(second, 'en/revalidation-top/second')).toBe(before)
}
// Invalidate the route pattern: the cached shell is shared by all values
// of the never-prerendered bottom parameter, not keyed by either request.
const response = await next.fetch('/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
pathname: '/[lang]/dynamic/[top]/[bottom]',
type: 'page',
}),
})
expect(response.status).toBe(200)
if (isDeploy) {
await readStableDeploymentGeneration(before)
} else {
const after = await retry(async () => {
const generation = await render(first, 'en/revalidation-top/first')
expect(generation).not.toBe(before)
return generation
})
expect(await render(second, 'en/revalidation-top/second')).toBe(after)
}
expect(
(await next.fetch('/fr/dynamic/revalidation-top/first')).status
).toBe(404)
})
it.each([
'/en/closed/unlisted',
'/fr/on-demand/revalidation-top/items/one',
])('does not admit an invalidated, unlisted URL: %s', async (pathname) => {
expect((await next.fetch(pathname)).status).toBe(404)
const response = await next.fetch('/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname }),
})
expect(response.status).toBe(200)
expect((await next.fetch(pathname)).status).toBe(404)
})
})
// @force-gate prefetching
describe('client route discovery', () => {
it.each([
['/en/catalog/nav-top/items/nav-bottom', 'en/nav-top/nav-bottom'],
['/es/on-demand/nav-top/items/nav-bottom', 'es/nav-top/nav-bottom'],
])(
'does not poison an admitted open suffix after prefetching a 404: %s',
async (pathname, params) => {
let allow404Act: ReturnType<typeof createRouterAct>
let admittedAct: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
allow404Act = createRouterAct(page, {
allowErrorStatusCodes: [404],
includeAppShellRequests: true,
})
admittedAct = createRouterAct(page, {
includeAppShellRequests: true,
})
},
})
await allow404Act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/fr/catalog/nav-top/items/nav-bottom"]'
)
.click()
})
// The adapter may return the same full RSC payload for both the tree
// and page prefetches. Require prefetching without coupling this setup
// to how that payload is partitioned across transport requests.
await admittedAct(async () => {
await browser
.elementByCss(`input[data-link-accordion="${pathname}"]`)
.click()
})
// The page can still have dynamic work after prefetch. Verify its final UI,
// rather than requiring a particular number of navigation requests.
await browser.elementByCss(`a[href="${pathname}"]`).click()
expect(await browser.elementById('params').text()).toBe(params)
await browser.refresh()
expect(await browser.elementById('params').text()).toBe(params)
}
)
it('does not reuse an admitted prefix when navigation must be a routing 404', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page, {
includeAppShellRequests: true,
})
},
})
// Require the admitted prefetch, but leave its tree/page response
// partitioning to the deployment adapter.
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/en/catalog/nav-top/items/nav-bottom"]'
)
.click()
})
await browser.elementById('navigate-rejected').click()
const navigationText = await browser
.elementByCss('#root-not-found, #params, #nested-not-found')
.text()
await browser.refresh()
expect(await browser.elementById('root-not-found').text()).toBe(
'Route not found'
)
expect(navigationText).toBe('Route not found')
})
})
})
export const unstable_paramMatching = { slug: 'blocking' } as const
export { PolicyPage as default } from '../../policy-page'
export const unstable_paramMatching = { slug: 'blocking' } as const
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export { PolicyPage as default } from '../../policy-page'
import { Suspense } from 'react'
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'dynamic',
} as const
export function generateStaticParams() {
return [{ top: 'seed' }]
}
async function Params({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p id="params">{`${top}/${bottom}`}</p>
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<>
<p id="shell-marker">{performance.now().toFixed(5)}</p>
<Suspense fallback={<p id="pending">waiting for params</p>}>
<Params params={params} />
</Suspense>
</>
)
}
export const unstable_paramMatching = { slug: 'fallback' } as const
export { PolicyPage as default } from '../../policy-page'
export const unstable_paramMatching = { slug: 'fallback' } as const
export function generateStaticParams() {
return [{ slug: 'seed' }]
}
export { PolicyPage as default } from '../../policy-page'
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <h1>Parameter matching runtime policies</h1>
}
import { Suspense } from 'react'
async function Params({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <p id="params">{slug}</p>
}
export function PolicyPage({ params }: { params: Promise<{ slug: string }> }) {
return (
<>
<p id="shell-marker">{performance.now().toFixed(5)}</p>
<Suspense fallback={<p id="pending">waiting for params</p>}>
<Params params={params} />
</Suspense>
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// The foreground matching policy must not change when Partial Prefetching
// is enabled. Axis A exercises the same assertions without it.
partialPrefetching: process.env.__NEXT_TEST_AXIS !== 'A',
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// @force-gate start
describe('param-matching-runtime', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function render(pathname: string, params: string) {
const res = await next.fetch(pathname)
const html = await res.text()
expect(res.status).toBe(200)
expect(html).toContain(`<p id="params">${params}</p>`)
const marker = html.match(/<p id="shell-marker">([^<]+)<\/p>/)?.[1]
expect(marker).toBeDefined()
// Inspect emitted HTML, not the serialized Suspense fallback in Flight.
return { marker, hasFallback: html.includes('<p id="pending">') }
}
describe.each(['blocking', 'blocking-no-seed'])('%s', (route) => {
it('prerenders the requested params before serving a cold document', async () => {
const a = await render(`/${route}/cold-a`, 'cold-a')
const b = await render(`/${route}/cold-b`, 'cold-b')
expect(a.hasFallback).toBe(false)
expect(b.hasFallback).toBe(false)
expect(a.marker).not.toBe(b.marker)
expect((await render(`/${route}/cold-a`, 'cold-a')).marker).toBe(a.marker)
})
it('shields concurrent cold requests with one concrete prerender', async () => {
const responses = await Promise.all(
Array.from({ length: 3 }, () =>
render(`/${route}/concurrent`, 'concurrent')
)
)
for (const response of responses) {
expect(response.hasFallback).toBe(false)
expect(response.marker).toBe(responses[0].marker)
}
expect((await render(`/${route}/concurrent`, 'concurrent')).marker).toBe(
responses[0].marker
)
})
})
describe.each(['fallback', 'fallback-no-seed'])('%s', (route) => {
it('serves a shared shell and resumes novel params for the first visitor', async () => {
const a = await render(`/${route}/first-a`, 'first-a')
const b = await render(`/${route}/first-b`, 'first-b')
expect(a.hasFallback).toBe(true)
expect(b.hasFallback).toBe(true)
expect(a.marker).toBe(b.marker)
})
it('upgrades the shell only when Partial Prefetching enables upgrades', async () => {
const pathname = `/${route}/upgrade`
const first = await render(pathname, 'upgrade')
expect(first.hasFallback).toBe(true)
const config = await next.getResolvedConfig()
if (config.partialPrefetching) {
await retry(async () => {
const upgraded = await render(pathname, 'upgrade')
expect(upgraded.hasFallback).toBe(false)
expect(upgraded.marker).not.toBe(first.marker)
})
} else {
const resumed = await render(pathname, 'upgrade')
expect(resumed.hasFallback).toBe(true)
expect(resumed.marker).toBe(first.marker)
}
})
})
it('starts with concrete outputs for build-time examples', async () => {
for (const route of ['blocking', 'fallback']) {
const first = await render(`/${route}/seed`, 'seed')
expect(first.hasFallback).toBe(false)
expect((await render(`/${route}/seed`, 'seed')).marker).toBe(first.marker)
}
})
it('blocks for a novel prerenderable prefix but keeps the tail dynamic', async () => {
const first = await render('/dynamic/top-a/bottom-a', 'top-a/bottom-a')
const sameTop = await render('/dynamic/top-a/bottom-b', 'top-a/bottom-b')
const otherTop = await render('/dynamic/top-b/bottom-a', 'top-b/bottom-a')
// The bottom value is resumed independently on each request, not captured
// in the cached output for top. A different top needs its own prerender.
expect(first.marker).toBe(sameTop.marker)
expect(first.marker).not.toBe(otherTop.marker)
})
})
export async function unstable_generateParamMatching() {
return { slug: 'fallback' }
}
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default function Page() {
return <p>Generated matching export</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import type { ParamMatching } from 'next'
export const policy = { slug: 'fallback' } satisfies ParamMatching
export const preservedLiteral: 'fallback' = policy.slug
export const invalidMode: ParamMatching<'slug'> = {
// @ts-expect-error Unsupported modes are rejected with contextual typing.
slug: 'unsupported',
}
export const invalidKey: ParamMatching<'slug'> = {
// @ts-expect-error Explicit key unions support strict type annotations.
category: 'blocking',
}
import type { ReactNode } from 'react'
// Deliberately no `as const`: object-property values naturally widen to string.
export const unstable_paramMatching = { lang: 'blocking' }
export default function Layout({ children }: { children: ReactNode }) {
return <section>{children}</section>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static matching export</p>
}
import type { ParamMatching } from 'next'
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
id: 'blocking',
} satisfies ParamMatching
export default function Layout({ children }: { children: ReactNode }) {
return <section>{children}</section>
}
import type { ParamMatching } from 'next'
export async function unstable_generateParamMatching(): Promise<
ParamMatching<'id'>
> {
return { id: 'blocking' }
}
export function generateStaticParams() {
return [{ id: 'one' }]
}
export default function Page() {
return <p>Optionally annotated configuration</p>
}
export async function unstable_generateParamMatching() {
return { slug: 'fallback', missing: 'fallback' }
}
export default function Page() {
return <p>Invalid generated keys</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
lang: 'blocking',
missing: 'fallback',
}
export default function Layout({ children }: { children: ReactNode }) {
return <section>{children}</section>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import execa from 'execa'
import { retry } from 'next-test-utils'
// Type checking requires local generated files, not a deployed HTTP response.
// @force-gate !deploy
describe('param-matching-types', () => {
const { next } = nextTestSetup({
files: __dirname,
})
beforeAll(async () => {
await next.fetch('/')
await retry(async () => {
expect(
await next.readFile(`${next.distDir}/types/validator.ts`)
).toContain('unstable_generateParamMatching')
})
})
it('accepts ordinary object literals and generator returns without as const', async () => {
const result = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect(result.stdout + result.stderr).toBe('')
expect(result.exitCode).toBe(0)
})
it.each([
['app/static/[lang]/layout.tsx', 'fixtures/invalid-layout.tsx'],
['app/generated/[slug]/page.tsx', 'fixtures/invalid-generator.tsx'],
])('still rejects invisible parameter keys in %s', async (file, fixture) => {
const original = await next.readFile(file)
try {
await next.patchFile(file, await next.readFile(fixture))
const result = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect(result.exitCode).not.toBe(0)
expect(result.stdout).toContain('"missing"')
expect(result.stdout).toContain("constraint 'never'")
} finally {
await next.patchFile(file, original)
}
})
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [{ "name": "next" }]
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
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'
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 unstable_paramMatching = { slug: 'not-found' } as const
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
// The page does not read slug, so its segment data can be shared. The matcher
// still needs to reject values that generateStaticParams did not return.
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>
}
'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: true,
// Keep the client-cache regression independent of completed-shell ISR keying.
partialPrefetching: false,
experimental: {
optimisticRouting: process.env.__NEXT_TEST_AXIS !== 'A',
varyParams: true,
prefetchInlining: true,
},
}
export default nextConfig
import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import type { PrerenderManifest } from 'next/dist/build'
import { createRouterAct } from 'router-act'
// @force-gate prefetching
describe('segment cache closed params (paramMatching: not-found)', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
it('rejects unlisted params at the routing level', async () => {
const allowedResponse = await next.fetch('/products/allowed', {
redirect: 'manual',
})
expect(allowedResponse.status).toBe(200)
const allowed = cheerio.load(await allowedResponse.text())
expect(allowed('#product-page').text()).toBe('Allowed product page')
// The product page always returns successful UI; it never calls notFound().
// An unlisted slug must be rejected by routing, without rendering either
// the products layout or its nested not-found boundary.
const rejectedResponse = await next.fetch('/products/rejected', {
redirect: 'manual',
})
expect(rejectedResponse.status).toBe(404)
const rejected = cheerio.load(await rejectedResponse.text())
expect(rejected('#root-not-found').text()).toBe('Route not found')
expect(
rejected('#products-layout, #product-page, #nested-not-found').length
).toBe(0)
// Verify that client route discovery is rejected too, rather than returning
// a successful generic /products/[slug] tree for an invalid parameter.
const headers = {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/_tree',
}
const allowedTree = await next.fetch('/products/allowed', { headers })
expect(allowedTree.status).toBe(200)
const rejectedTree = await next.fetch('/products/rejected', { headers })
expect(rejectedTree.status).toBe(404)
// Build artifacts are only available locally. The HTTP assertions above
// also run against deployments and verify the externally visible contract.
if (isNextStart) {
const manifest: PrerenderManifest = await next.readJSON(
'.next/prerender-manifest.json'
)
expect(manifest.dynamicRoutes['/products/[slug]'].fallback).toBe(false)
expect(
Object.keys(manifest.routes).filter((path) =>
path.startsWith('/products/')
)
).toEqual(['/products/allowed'])
}
})
it('does not reuse a prefetched 404 for an allowed parameter value', async () => {
const response = await next.fetch('/products/allowed')
expect(response.status).toBe(200)
expect(await response.text()).toContain('id="product-page"')
let act: ReturnType<typeof createRouterAct>
const statuses: number[] = []
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page, {
allowErrorStatusCodes: [404],
includeAppShellRequests: true,
})
page.on('response', (response) => {
if (
response.request().headers().rsc &&
new URL(response.url()).pathname === '/products/rejected'
) {
statuses.push(response.status())
}
})
},
})
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/products/rejected"]')
.click()
})
expect(statuses).toContain(404)
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/products/allowed"]')
.click()
},
{ includes: 'Allowed product page' }
)
await act(async () => {
await browser.elementByCss('a[href="/products/allowed"]').click()
}, 'no-requests')
expect(
await browser.elementByCss('#product-page, #root-not-found').text()
).toBe('Allowed product page')
expect(await browser.hasElementByCss('#root-not-found')).toBe(false)
})
it('does not reuse an allowed route for a parameter value that must 404', async () => {
const allowedResponse = await next.fetch('/products/allowed')
expect(allowedResponse.status).toBe(200)
expect(await allowedResponse.text()).toContain('id="product-page"')
// The document request establishes the expected route-level 404, rather
// than the nested not-found boundary inside the products layout.
const response = await next.fetch('/products/rejected')
expect(response.status).toBe(404)
const html = await response.text()
expect(html).toContain('id="root-not-found"')
expect(html).not.toContain('id="products-layout"')
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page, {
allowErrorStatusCodes: [404],
includeAppShellRequests: true,
})
},
})
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/products/allowed"]')
.click()
},
{ includes: 'Allowed product page' }
)
// Learning /products/[slug] must not imply that every slug can match it,
// even when none of the cached segments read slug.
// This link opts out of prefetching. Optimistic navigation must not reuse
// the allowed page without checking whether the new parameter can match.
// A 404 may fall back to a document navigation, which router-act does not
// support, so wait for the rendered result outside act.
await browser.elementById('navigate-rejected').click()
const navigationText = await browser
.elementByCss('#product-page, #root-not-found, #nested-not-found')
.text()
await browser.refresh()
expect(await browser.elementByCss('#root-not-found').text()).toBe(
'Route not found'
)
expect(await browser.hasElementByCss('#products-layout')).toBe(false)
expect(navigationText).toBe('Route not found')
})
})
import { connection } from 'next/server'
export async function unstable_generateParamMatching() {
await connection()
return { slug: 'blocking' }
}
export default function Page() {
return <p>connection</p>
}
import { cookies } from 'next/headers'
export async function unstable_generateParamMatching() {
await cookies()
return { slug: 'blocking' }
}
export default function Page() {
return <p>cookies</p>
}
import { draftMode } from 'next/headers'
export async function unstable_generateParamMatching() {
await draftMode()
return { slug: 'blocking' }
}
export default function Page() {
return <p>draft mode</p>
}
import { headers } from 'next/headers'
export async function unstable_generateParamMatching() {
await headers()
return { slug: 'blocking' }
}
export default function Page() {
return <p>headers</p>
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { navigation } from 'next/cache'
export async function unstable_generateParamMatching() {
await navigation()
return { slug: 'blocking' }
}
export default function Page() {
return <p>navigation</p>
}
import { prefetch } from 'next/cache'
export async function unstable_generateParamMatching() {
await prefetch()
return { slug: 'blocking' }
}
export default function Page() {
return <p>prefetch</p>
}
async function getMatching() {
'use cache: private'
return { slug: 'blocking' }
}
export async function unstable_generateParamMatching() {
return getMatching()
}
export default function Page() {
return <p>private cache</p>
}
import { revalidatePath } from 'next/cache'
export async function unstable_generateParamMatching() {
revalidatePath('/')
return { slug: 'blocking' }
}
export default function Page() {
return <p>revalidate</p>
}
import { lang } from 'next/root-params'
export async function unstable_generateParamMatching() {
await lang()
return { slug: 'blocking' }
}
export default function Page() {
return <p>root params</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('param-matching-generator-errors', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
afterEach(async () => {
await next.stop()
})
async function buildRoute(route: string) {
const { exitCode, cliOutput } = await next.build({
args: ['--debug-build-paths', `app/[lang]/${route}/[slug]/page.tsx`],
})
expect(exitCode).toBe(1)
return cliOutput
}
it.each([
['cookies', 'cookies()'],
['headers', 'headers()'],
['connection', 'connection()'],
['draft-mode', 'draftMode()'],
['prefetch', 'prefetch()'],
['navigation', 'navigation()'],
])(
'names the matching generator when %s is unavailable',
async (route, api) => {
const output = await buildRoute(route)
expect(output).toContain(
`Route /[lang]/${route}/[slug] used \`${api}\` inside \`unstable_generateParamMatching\`. This is not supported because \`unstable_generateParamMatching\` runs at build time`
)
}
)
it('names the matching generator when private caching needs a request', async () => {
const output = await buildRoute('private-cache')
expect(output).toContain(
'`"use cache: private"` needs an active request, so it can\'t be used during `unstable_generateParamMatching`'
)
})
it('names the matching generator before the general render-phase revalidation error', async () => {
const output = await buildRoute('revalidate')
expect(output).toContain(
'`revalidatePath("/")` can\'t be called inside `unstable_generateParamMatching`. Call it from a Server Action or Route Handler instead.'
)
})
it('does not suggest that the matching generator receives parent gSP values', async () => {
const output = await buildRoute('root-params')
expect(output).toContain(
"Route /[lang]/root-params/[slug] used `import('next/root-params').lang()` inside `unstable_generateParamMatching`, but the `lang` parameter is not available in this build-time generator."
)
expect(output).not.toContain('was not provided by a parent')
})
})
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'blocking' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export async function unstable_generateParamMatching() {
return { lang: 'not-found' } as const
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'blocking' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'not-found' } as const
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { slug: 'fallback' } as const
export function generateStaticParams() {
return [{ lang: 'en', slug: 'example' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
import type { ReactNode } from 'react'
export default function Layout({
children,
other,
}: {
children: ReactNode
other: ReactNode
}) {
return (
<>
{children}
{other}
</>
)
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'not-found' } as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export function generateStaticParams() {
return [{ lang: 'fr' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { lang: 'not-found' } as const
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { locale: 'not-found' } as const
export function generateStaticParams() {
return [{ locale: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export async function unstable_generateParamMatching() {
return { locale: 'not-found' } as const
}
export function generateStaticParams() {
return [{ locale: 'en' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { id: 'blocking' } as const
export function generateStaticParams() {
return [{ id: 'one' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { id: 'fallback' } as const
export function generateStaticParams() {
return [{ id: 'one' }]
}
export default function Page() {
return <p>Static page</p>
}
export const unstable_paramMatching = { slug: 'not-found' } as const
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return <p>Static page</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = { locale: 'not-found' } as const
export function generateStaticParams() {
return [{ locale: 'en' }]
}
export default function Layout({
children,
other,
}: {
children: ReactNode
other: ReactNode
}) {
return (
<>
{children}
{other}
</>
)
}
export default function Page() {
return <p>Children slot</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: false,
}
export default nextConfig
import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'node:path'
describe.each([
['explicit-mismatch', '/[lang]/a', '/[lang]/b'],
['missing-sibling', '/[lang]/a', '/[lang]/b'],
['missing-policy-key', '/[lang]/a', '/[lang]/b/[slug]'],
['inherited-override', '/[lang]/a', '/[lang]/b'],
['generated-missing', '/[lang]/a', '/[lang]/b'],
['missing-ancestor', '/[lang]/a', '/[lang]'],
['route-group-missing', '/[lang]/a', '/[lang]/b'],
['parallel-missing', '/[lang]', null],
] as const)(
'not-found parameter coherence: %s',
(fixture, closedRoute, openRoute) => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'fixtures', fixture)),
'app/layout.tsx': new FileRef(join(__dirname, 'app/layout.tsx')),
'next.config.ts': new FileRef(join(__dirname, 'next.config.ts')),
},
skipStart: true,
})
it('rejects a parameter that is not explicitly closed in every route', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain('Parameter "lang"')
expect(cliOutput).toContain('must explicitly configure "not-found"')
expect(cliOutput).toContain(closedRoute)
if (openRoute !== null) {
expect(cliOutput).toContain(openRoute)
} else {
expect(cliOutput).toContain('parallel branch')
}
})
}
)
describe('coherent not-found parameter configurations', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'fixtures/valid')),
'app/layout.tsx': new FileRef(join(__dirname, 'app/layout.tsx')),
'next.config.ts': new FileRef(join(__dirname, 'next.config.ts')),
},
skipStart: true,
})
it('accepts inheritance, explicit agreement, and unrelated parameter definitions', async () => {
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('must explicitly configure "not-found"')
expect(exitCode).toBe(0)
// Check that accepting the policies still produces each route's outputs.
// If the manifest changes, preserve that scenario rather than exposing
// internals solely to keep these assertions working.
const manifest = await next.readJSON('.next/prerender-manifest.json')
// Agreement on matching policy does not require identical allowed values.
expect(manifest.routes['/en/a']).toBeDefined()
expect(manifest.routes['/fr/b']).toBeDefined()
// These slug parameters have distinct definitions despite the same name.
expect(manifest.routes['/products/allowed']).toBeDefined()
expect(manifest.routes['/blog/allowed']).toBeDefined()
expect(manifest.routes['/explicit/en/a']).toBeDefined()
expect(manifest.routes['/explicit/en/b']).toBeDefined()
expect(manifest.routes['/slots/en']).toBeDefined()
expect(manifest.routes['/open/one/a']).toBeDefined()
expect(manifest.routes['/open/one/b']).toBeDefined()
})
})
export const unstable_paramMatching = {
lang: 'blocking',
} as const
export default function Page() {
return <p>Main overrides the lang policy.</p>
}
export default function Page() {
return <p>Sidebar inherits the closed lang policy.</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = {
lang: 'not-found',
} as const
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Layout({
children,
main,
sidebar,
}: {
children: ReactNode
main: ReactNode
sidebar: ReactNode
}) {
return (
<>
{children}
{main}
{sidebar}
</>
)
}
export default function Page() {
return <p>Children inherit the closed lang policy.</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('param-matching-parallel-inheritance', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('rejects an override that conflicts with a sibling inherited policy', async () => {
const { exitCode, cliOutput } = await next.build()
// All slots match /[lang]. Opening @main must not also open @sidebar,
// which still inherits lang: 'not-found' from their shared layout.
expect(cliOutput).toContain(
'conflicting parallel parameter matching modes for parameter "lang"'
)
expect(exitCode).toBe(1)
})
it('allows all parallel branches to explicitly replace the inherited policy', async () => {
for (const file of [
'app/[lang]/page.tsx',
'app/[lang]/@sidebar/page.tsx',
]) {
await next.patchFile(
file,
`export const unstable_paramMatching = { lang: 'blocking' } as const\n${await next.readFile(file)}`
)
}
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain(
'conflicting parallel parameter matching modes'
)
expect(exitCode).toBe(0)
})
})
export const unstable_paramMatching = {
bottom: 'dynamic',
} as const
export { default } from '../../../param-page'
export const unstable_paramMatching = {}
export function generateStaticParams() {
return [{ bottom: 'seed' }]
}
export { default } from '../../../param-page'
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ bottom: 'seed' }]
}
export { default } from '../../../param-page'
export async function unstable_generateParamMatching() {
return { bottom: 'fallback' } as const
}
export function generateStaticParams() {
return [{ bottom: 'seed' }]
}
export { default } from '../../../param-page'
export function generateStaticParams() {
return [{ bottom: 'seed' }]
}
export { default } from '../../../param-page'
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
type Props = { params: Promise<{ lang: string; bottom: string }> }
async function Params({ params }: Props) {
const { lang, bottom } = await params
return <p>{`${lang}/${bottom}`}</p>
}
export default function Page({ params }: Props) {
return (
<Suspense fallback={<p>Waiting for lang and bottom</p>}>
<Params params={params} />
</Suspense>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import type { PrerenderManifest } from 'next/dist/build'
describe('param-matching-root-fallback', () => {
const { next } = nextTestSetup({
files: __dirname,
})
let manifest: PrerenderManifest
beforeAll(async () => {
// These build artifacts distinguish a servable fallback from a blocking
// render used only for hints. If their representation changes, preserve
// that regression coverage rather than exposing internals for this test.
manifest = JSON.parse(await next.readFile('.next/prerender-manifest.json'))
})
it('blocks an unresolved root parameter without matching configuration', () => {
expect(
manifest.dynamicRoutes['/[lang]/inferred/[bottom]'].fallback
).toBeNull()
})
it('retains the inferred generic render for build-time hints without matching configuration', async () => {
// Blocking results are not served, but the legacy build still renders
// them to collect hints. Only explicit matching may skip such a render.
expect(
await next.readJSON('.next/server/app/[lang]/inferred/[bottom].meta')
).toBeDefined()
})
it.each(['empty', 'fallback', 'generated', 'dynamic'])(
'preserves root-parameter blocking for the %s matching export',
(route) => {
// lang is a root parameter because the HTML layout is at app/[lang].
// Neither an empty export nor configuring only bottom should change
// the existing requirement to block until root parameters are known.
expect(
manifest.dynamicRoutes[`/[lang]/${route}/[bottom]`].fallback
).toBeNull()
}
)
it.each(['inferred', 'empty', 'fallback', 'generated', 'dynamic'])(
'keeps the %s fallback available once the root parameter is known',
(route) => {
expect(
typeof manifest.dynamicRoutes[`/en/${route}/[bottom]`].fallback
).toBe('string')
}
)
})
export async function unstable_generateParamMatching() {
return { top: 'blocking', bottom: 'fallback' } as const
}
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="sidebar-page">Sidebar page</p>
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="main-page">Main page</p>
}
import type { ReactNode } from 'react'
export default function Layout({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<html>
<body>
{children}
{sidebar}
</body>
</html>
)
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="main-page">Main page</p>
}
export async function unstable_generateParamMatching() {
return { top: 'blocking', bottom: 'fallback' } as const
}
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="sidebar-page">Sidebar page</p>
}
import type { ReactNode } from 'react'
export default function Layout({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<html>
<body>
{children}
{sidebar}
</body>
</html>
)
}
export async function unstable_generateParamMatching() {
return { top: 'blocking', bottom: 'fallback' } as const
}
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="sidebar-page">Sidebar page</p>
}
export const unstable_paramMatching = {
top: 'blocking',
bottom: 'fallback',
} as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p id="main-page">Main page</p>
}
import type { ReactNode } from 'react'
export default function Layout({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<html>
<body>
{children}
{sidebar}
</body>
</html>
)
}
// Valid on its own, but the main slot explicitly configures top as fallback.
export const unstable_paramMatching = { bottom: 'blocking' } as const
export default function Page() {
return <p>Sidebar page</p>
}
export const unstable_paramMatching = { top: 'fallback' } as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p>Main page</p>
}
import type { ReactNode } from 'react'
export default function Layout({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<html>
<body>
{children}
{sidebar}
</body>
</html>
)
}
// Closing bottom must not silently close the explicitly blocking top param.
export const unstable_paramMatching = { bottom: 'not-found' } as const
export function generateStaticParams() {
return [{ top: 't1', bottom: 'b1' }]
}
export default function Page() {
return <p>Inherited parameter policy</p>
}
import type { ReactNode } from 'react'
export const unstable_paramMatching = { top: 'blocking' } as const
export default function Layout({ children }: { children: ReactNode }) {
return children
}
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'node:path'
describe.each(['aligned', 'grouped-sidebar', 'grouped-children'])(
'param-matching parallel route order: %s',
(fixture) => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'fixtures', fixture)),
'next.config.ts': new FileRef(join(__dirname, 'next.config.ts')),
},
skipStart: true,
})
it('uses URL parameter order regardless of the depth of a parallel branch', async () => {
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('must be ordered')
expect(exitCode).toBe(0)
await next.start({ skipBuild: true })
for (const pathname of ['/t1/b1', '/t2/b2']) {
const $ = await next.render$(pathname)
expect($('#main-page').text()).toBe('Main page')
expect($('#sidebar-page').text()).toBe('Sidebar page')
}
})
}
)
describe.each([
['incompatible', 'blocking'],
['inherited-not-found', 'not-found'],
])('param-matching incoherent composition: %s', (fixture, bottomMode) => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'fixtures', fixture)),
'next.config.ts': new FileRef(join(__dirname, 'next.config.ts')),
},
skipStart: true,
})
it('rejects policies that become incoherent through composition', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(
`parameter "bottom" uses "${bottomMode}" after parameter "top" uses a later matching phase`
)
})
})
export const unstable_paramMatching = {
bottom: 'blocking',
} as const
export { default } from '../../../param-page'
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export { default } from '../../../../param-page'
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
// There are no example params to validate a more specific shell. Opt out of
// instant validation so this test can inspect the inferred empty-shell mode.
export const instant = false
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p>{`${top}/${bottom}`}</p>
}
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export { default } from '../../../param-page'
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
type Props = { params: Promise<{ top: string; bottom: string }> }
async function Params({ params }: Props) {
const { top, bottom } = await params
return <p>{`${top}/${bottom}`}</p>
}
export default function Page({ params }: Props) {
return (
<Suspense fallback={<p>Waiting for top and bottom</p>}>
<Params params={params} />
</Suspense>
)
}
export const unstable_paramMatching = {
bottom: 'fallback',
} as const
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p>{`${top}/${bottom}`}</p>
}
import { Suspense, type ReactNode } from 'react'
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return (
<section data-top={top}>
<Suspense fallback={<p>Waiting for bottom</p>}>{children}</Suspense>
</section>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import type { PrerenderManifest } from 'next/dist/build'
describe('param-matching-unseeded-prefix', () => {
const { next } = nextTestSetup({
files: __dirname,
})
let manifest: PrerenderManifest
beforeAll(async () => {
// Inspect the build contract to distinguish runtime-prerenderable params
// from always-dynamic tails. If this format changes, reconstruct those
// scenarios rather than exposing internals to preserve these assertions.
manifest = JSON.parse(await next.readFile('.next/prerender-manifest.json'))
})
it('keeps both params dynamic when neither has examples or an explicit policy', () => {
expect(
manifest.dynamicRoutes['/inferred/[top]/[bottom]']
.remainingPrerenderableParams
).toBeUndefined()
})
it.each(['blocking', 'fallback'])(
'infers a prerenderable prefix before bottom: %s without build-time examples',
(mode) => {
const matcher = manifest.dynamicRoutes[`/${mode}/[top]/[bottom]`]
// There is no generateStaticParams in these routes. An explicit
// prerenderable bottom requires top to be prerenderable too: an inferred
// dynamic top would make the effective matching order incoherent.
expect(
matcher.remainingPrerenderableParams?.map(({ paramName }) => paramName)
).toEqual(['top', 'bottom'])
}
)
it('infers fallback for an unconfigured prefix with a non-empty shell', () => {
expect(
typeof manifest.dynamicRoutes['/fallback/[top]/[bottom]'].fallback
).toBe('string')
})
it('keeps an inferred prefix blocking before an explicitly blocking param', () => {
expect(
manifest.dynamicRoutes['/blocking/[top]/[bottom]'].fallback
).toBeNull()
})
it('infers blocking for an empty shell without build-time examples', () => {
const matcher = manifest.dynamicRoutes['/empty/[top]/[bottom]']
expect(matcher.fallback).toBeNull()
expect(
matcher.remainingPrerenderableParams?.map(({ paramName }) => paramName)
).toEqual(['top', 'bottom'])
})
it('keeps unconfigured params after the explicit policy dynamic', () => {
const matcher =
manifest.dynamicRoutes['/dynamic-tail/[top]/[bottom]/[tail]']
expect(
matcher.remainingPrerenderableParams?.map(({ paramName }) => paramName)
).toEqual(['top', 'bottom'])
expect(
matcher.fallbackRouteParams?.map(({ paramName }) => paramName)
).toEqual(['top', 'bottom', 'tail'])
})
it('infers blocking for top while retaining the explicit bottom fallback', () => {
expect(
manifest.dynamicRoutes['/seeded-empty/[top]/[bottom]'].fallback
).toBeNull()
expect(
typeof manifest.dynamicRoutes['/seeded-empty/t1/[bottom]'].fallback
).toBe('string')
})
})
......@@ -154,6 +154,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/build/static-paths/app.js",
"/node_modules/next/dist/build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree.js",
"/node_modules/next/dist/build/static-paths/pages.js",
"/node_modules/next/dist/build/static-paths/param-matching.js",
"/node_modules/next/dist/build/static-paths/utils.js",
"/node_modules/next/dist/build/swc/helpers.js",
"/node_modules/next/dist/build/swc/index.js",
......
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