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(
getRouteRegex(normalizeAppPath(originalAppPath)).groups
)
: undefined
) {
notFoundParams = Object.keys(
getRouteRegex(normalizeAppPath(originalAppPath)).groups
)
}
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)
}
......
This diff is collapsed.
......@@ -94,11 +94,14 @@ export function extractPathnameRouteParamSegmentsFromLoaderTree(
}>
params: Params
} {
const pathnameRouteParamSegments: Array<{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> = []
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(
(route) => route.pathname === pathname
)
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 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
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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