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

Use structural React keys during server rendering (#98944)

## Summary

Use structural React keys during server rendering so an HTML prerender
can resume without rewriting React's postponed state when route params
become known. Browser keys and router-cache identity are unchanged.

For example, `/products/[slug]` previously prerendered layout boundaries
with a key containing an opaque slug placeholder. Resuming
`/products/shoe` produced a different key, so Next.js substituted `shoe`
into the serialized React state before handing it back to React. Both
server passes now use `slug|d`. The browser still uses `slug|shoe|d`,
preserving template remounts and back/forward state behavior.

The server only renders the active entry at each layout-router position,
so it does not need parameter values to distinguish cached browser
entries. React keys are not embedded in the HTML; hydration derives its
concrete keys from the request's route state.

- Use segment name/type for server layout keys and structural route
paths for the server head key. Server keys always omit search params.
The existing browser-module variant mechanism selects the concrete key
implementation for browser bundles in both Webpack and Turbopack.
- Remove placeholder substitution and the request-params argument from
postponed-state parsing. Persist only fallback param names for render
staging; React's postponed state no longer needs to be searched or
rewritten.
- Simplify the remaining opaque fallback map to param name →
placeholder. Its dynamic-param type slot is unused after removing
interpolation. Parameter wrappers still control suspension; this does
not make unknown params available to application code.
- Test server and browser keys directly, including catch-all/intercepted
segments and search params. Update the action-only resume fixture's
single assertion on the resume-metadata format so its three cases reach
their behavioral checks for action execution, revalidation, and
`notFound()` with names-only metadata.

This refactor is independently landable against `canary` and is now the
base of the parameter-matching stack: #98944 → #98891 → #98892 → #98893
→ #97393. It supersedes #98890. It retains internal opaque placeholders
but removes their role in matching React's postponed state. No new
integration fixtures are needed.

## Verification

Latest cleanup:

- 126 focused unit tests and 4 snapshots pass in both default and Cache
Components/Webpack configurations.
- 34 production Webpack tests pass across `fallback-shells`,
`partial-fallback-shell-upgrade`,
`action-only-fallback-resume-data-cache`, and
`resuming-head-runtime-search-param`; 4 existing tests remain skipped.
The three action-only resume cases now reach and pass their behavioral
assertions.

Earlier commits also passed existing production and dev Webpack coverage
for back/forward state, template remounts, base-path params,
nested/parallel/intercepted routes, form-state hydration, and
standalone/edge output.

A reviewer verified this head under Turbopack using a native binary
built from the same commit: a broader unit selection passed (144 tests,
the focused set above plus the remaining router-reducer suites), the
`packages/next` type check was clean, and 33 production e2e tests passed
across `fallback-shells`, `partial-fallback-shell-upgrade`, and
`action-only-fallback-resume-data-cache`.

<!-- NEXT_JS_LLM -->
parent 0927d3e8
......@@ -14,6 +14,7 @@ pub static BROWSER_VARIANT_MODULES: &[&str] = &[
"client/components/instant-samples",
"client/components/instant-validation/impl",
"client/components/navigation-dynamic-rendering",
"client/components/router-reducer/create-segment-key",
"client/components/server-async-storage",
"client/components/unstable-rethrow",
];
......@@ -10,6 +10,7 @@ export const browserVariantModules = [
'client/components/instant-samples',
'client/components/instant-validation/impl',
'client/components/navigation-dynamic-rendering',
'client/components/router-reducer/create-segment-key',
'client/components/server-async-storage',
'client/components/unstable-rethrow',
] as const
......@@ -498,17 +498,9 @@ function Router({
//
// The `key` is used to remount the component whenever the head moves to
// a different segment.
const [headCacheNode, headKey, headKeyWithoutSearchParams] = matchingHead
const [headCacheNode, headKey] = matchingHead
head = (
<Head
key={
// Necessary for PPR: omit search params from the key to match prerendered keys
typeof window === 'undefined' ? headKeyWithoutSearchParams : headKey
}
headCacheNode={headCacheNode}
/>
)
head = <Head key={headKey} headCacheNode={headCacheNode} />
} else {
head = null
}
......
......@@ -36,7 +36,7 @@ import {
InstantValidationBoundaryContext,
RenderValidationBoundaryAtThisLevel,
} from './instant-validation/boundary'
import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
import { createSegmentKey } from './router-reducer/create-segment-key'
import {
useRouterBFCache,
type RouterBFCacheEntry,
......@@ -564,11 +564,13 @@ export default function OuterLayoutRouter({
[parallelRouterKey]
: parentSegmentPath.concat([parentTreeSegment, parallelRouterKey])
// The "state" key of a segment is the one passed to React — it represents the
// identity of the UI tree. Whenever the state key changes, the tree is
// recreated and the state is reset. In the App Router model, search params do
// not cause state to be lost, so two segments with the same segment path but
// different search params should have the same state key.
// The "state" key of a segment is the one passed to React. In the browser it
// represents the identity of the UI tree. Whenever the state key changes,
// the tree is recreated and the state is reset. In the App Router model,
// search params do not cause state to be lost, so two segments with the same
// segment path but different search params should have the same state key.
// On the server, the key describes the segment's structure instead, so it
// stays the same when unknown params become known during HTML resume.
//
// The "cache" key of a segment, however, *does* include the search params, if
// it's possible that the segment accessed the search params on the server.
......@@ -591,7 +593,7 @@ export default function OuterLayoutRouter({
const activeSegment = activeTree[0]
const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null
const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params
const activeStateKey = createSegmentKey(activeSegment, true) // no search params
// At each level of the route tree, not only do we render the currently
// active segment — we also render the last N segments that were active at
......@@ -610,7 +612,6 @@ export default function OuterLayoutRouter({
const cacheNode = bfcacheEntry.cacheNode
const stateKey = bfcacheEntry.stateKey
const segment = tree[0]
/*
- Error boundary
- Only renders error boundary if error component is provided.
......
// In the browser, React keys include concrete params so navigation preserves
// or resets component state according to the segment's actual identity.
export { createRouterCacheKey as createSegmentKey } from './create-router-cache-key'
import { createRouterCacheKey } from './create-router-cache-key'
import { createSegmentKey } from './create-segment-key'
import { createSegmentKey as createBrowserSegmentKey } from './create-segment-key.browser'
describe('createSegmentKey on the server', () => {
it.each(['d', 'c', 'oc', 'di(.)', 'ci(.)'] as const)(
'keeps %s keys stable between prerendering and resuming',
(paramType) => {
const fallbackKey = createSegmentKey([
'slug',
'%%drp:slug:abc123%%',
paramType,
null,
])
expect(fallbackKey).toBe(`slug|${paramType}`)
expect(createSegmentKey(['slug', 'first', paramType, null])).toBe(
fallbackKey
)
expect(createSegmentKey(['slug', 'second/third', paramType, null])).toBe(
fallbackKey
)
}
)
it('distinguishes param names and segment types', () => {
const keys = [
createSegmentKey(['slug', 'value', 'd', null]),
createSegmentKey(['other', 'value', 'd', null]),
createSegmentKey(['slug', 'value', 'c', null]),
createSegmentKey(['slug', 'value', 'oc', null]),
createSegmentKey(['slug', 'value', 'di(.)', null]),
createSegmentKey(['slug', 'value', 'ci(.)', null]),
]
expect(new Set(keys).size).toBe(keys.length)
})
it.each(['', 'catalog', '__DEFAULT__', '__PAGE__'])(
'preserves the static segment %j',
(segment) => {
expect(createSegmentKey(segment)).toBe(segment)
}
)
it.each([undefined, false, true])(
'always omits search params, even with withoutSearchParameters=%s',
(withoutSearchParameters) => {
expect(
createSegmentKey('__PAGE__?{"q":"first"}', withoutSearchParameters)
).toBe('__PAGE__')
expect(
createSegmentKey('__PAGE__?{"q":"second"}', withoutSearchParameters)
).toBe('__PAGE__')
}
)
})
describe('createSegmentKey in the browser', () => {
it('re-exports the router cache key implementation', () => {
expect(createBrowserSegmentKey).toBe(createRouterCacheKey)
})
it.each(['d', 'c', 'oc', 'di(.)', 'ci(.)'] as const)(
'includes concrete param values in %s keys',
(paramType) => {
expect(createBrowserSegmentKey(['slug', 'first', paramType, null])).toBe(
`slug|first|${paramType}`
)
expect(
createBrowserSegmentKey(['slug', 'second/third', paramType, null])
).toBe(`slug|second/third|${paramType}`)
}
)
it.each([undefined, false, true])(
'respects withoutSearchParameters=%s',
(withoutSearchParameters) => {
const segment = '__PAGE__?{"q":"first"}'
expect(createBrowserSegmentKey(segment, withoutSearchParameters)).toBe(
withoutSearchParameters ? '__PAGE__' : segment
)
}
)
})
import type { Segment } from '../../../shared/lib/app-router-types'
import { createRouterCacheKey } from './create-router-cache-key'
// React uses these keys to find suspended subtrees when resuming HTML. They
// must be the same before and after route params and search params are known.
// The browser uses the concrete keys instead, so navigation still resets or
// preserves state as appropriate. Its bundle uses create-segment-key.browser.ts.
// React keys are not embedded in the HTML.
export function createSegmentKey(
segment: Segment,
// Server keys always omit search params, regardless of this browser option.
_withoutSearchParameters?: boolean
): string {
if (Array.isArray(segment)) {
return `${segment[0]}|${segment[2]}`
}
return createRouterCacheKey(segment, true)
}
......@@ -3,25 +3,24 @@ import type {
CacheNode,
} from '../../../../shared/lib/app-router-types'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import { createRouterCacheKey } from '../create-router-cache-key'
import { createSegmentKey } from '../create-segment-key'
export function findHeadInCache(
cache: CacheNode,
parallelRoutes: FlightRouterState[1]
): [CacheNode, string, string] | null {
return findHeadInCacheImpl(cache, parallelRoutes, '', '')
): [CacheNode, string] | null {
return findHeadInCacheImpl(cache, parallelRoutes, '')
}
function findHeadInCacheImpl(
cache: CacheNode,
parallelRoutes: FlightRouterState[1],
keyPrefix: string,
keyPrefixWithoutSearchParams: string
): [CacheNode, string, string] | null {
keyPrefix: string
): [CacheNode, string] | null {
const isLastItem = Object.keys(parallelRoutes).length === 0
if (isLastItem) {
// Returns the entire Cache Node of the segment whose head we will render.
return [cache, keyPrefix, keyPrefixWithoutSearchParams]
return [cache, keyPrefix]
}
// First try the 'children' parallel route if it exists
......@@ -50,14 +49,14 @@ function findHeadInCacheImpl(
continue
}
const cacheKey = createRouterCacheKey(segment)
const cacheKeyWithoutSearchParams = createRouterCacheKey(segment, true)
// This key identifies the Head component, not a cache entry. On the
// server it must match even when resuming with previously unknown params.
const segmentKey = createSegmentKey(segment)
const item = findHeadInCacheImpl(
childCacheNode,
childParallelRoutes,
keyPrefix + '/' + cacheKey,
keyPrefix + '/' + cacheKeyWithoutSearchParams
keyPrefix + '/' + segmentKey
)
if (item) {
......
......@@ -3007,10 +3007,16 @@ async function renderAppPage(
null
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
// Keep the placeholder map for dev's separate prerender validation. The
// request store only needs names to defer params during a staged render.
const stagedFallbackParams =
getRequestMeta(req, 'stagedFallbackParams') ?? null
const stagedFallbackParamNames =
postponedState?.stagedFallbackParams !== undefined
? postponedState.stagedFallbackParams
: (getRequestMeta(req, 'stagedFallbackParams') ?? null)
: stagedFallbackParams
? new Set(stagedFallbackParams.keys())
: null
const hmrRefreshHash = getRequestMeta(req, 'hmrRefreshHash')
const createRequestStore = createRequestStoreForRender.bind(
......@@ -3025,7 +3031,7 @@ async function renderAppPage(
isHmrRefresh,
serverComponentsHmrCache,
renderResumeDataCache,
stagedFallbackParams,
stagedFallbackParamNames,
hmrRefreshHash
)
const requestStore = createRequestStore()
......@@ -3354,7 +3360,6 @@ function prepareAppPage(
} else {
postponedState = parsePostponedState(
renderOpts.postponed,
interpolatedParams,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
)
......@@ -6768,7 +6773,9 @@ export async function runValidationInDevFromSnapshot(
isHmrRefresh: message.request.isHmrRefresh,
hmrRefreshHash: message.request.hmrRefreshHash,
serverComponentsHmrCache: undefined,
stagedFallbackParams: fallbackRouteParams,
stagedFallbackParams: fallbackRouteParams
? new Set(fallbackRouteParams.keys())
: null,
})
const staticInputs = toDevValidationInputs(message.staticInputs, requestStore)
......
import type {
OpaqueFallbackRouteParamEntries,
OpaqueFallbackRouteParams,
} from '../../server/request/fallback-params'
import { getDynamicParam } from '../../shared/lib/router/utils/get-dynamic-param'
import type { Params } from '../request/params'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import {
createPrerenderResumeDataCache,
createRenderResumeDataCache,
......@@ -39,7 +34,7 @@ export type DynamicDataPostponedState = {
* metadata when this field is absent. `null` explicitly means no fallback
* params.
*/
readonly stagedFallbackParams?: OpaqueFallbackRouteParams | null
readonly stagedFallbackParams?: ReadonlySet<string> | null
/**
* The immutable resume data cache.
......@@ -61,7 +56,7 @@ export type DynamicHTMLPostponedState = {
* this set, and `null` means the prerender had no fallback params. Unlike the
* data state, it never falls back to request metadata.
*/
readonly stagedFallbackParams: OpaqueFallbackRouteParams | null
readonly stagedFallbackParams: ReadonlySet<string> | null
/**
* The postponed data used by React.
......@@ -148,13 +143,15 @@ export async function getDynamicHTMLPostponedState(
)
}
const replacements: OpaqueFallbackRouteParamEntries = Array.from(
fallbackRouteParams.entries()
const fallbackParamsString = JSON.stringify(
Array.from(fallbackRouteParams.keys())
)
const replacementsString = JSON.stringify(replacements)
// Serialized as `<replacements.length><replacements><data>`
const postponedString = `${replacementsString.length}${replacementsString}${dataString}`
// Render staging only needs to know which params were unknown. Their opaque
// placeholders and types aren't needed to resume, since React's server keys
// don't depend on param values.
// Serialized as `<fallbackParams.length><fallbackParams><data>`
const postponedString = `${fallbackParamsString.length}${fallbackParamsString}${dataString}`
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return serializePostponedState(
......@@ -175,14 +172,13 @@ export async function getDynamicDataPostponedState(
): Promise<string> {
let postponedString = 'null'
if (fallbackRouteParams !== undefined) {
const replacements: OpaqueFallbackRouteParamEntries = fallbackRouteParams
? Array.from(fallbackRouteParams.entries())
: []
const replacementsString = JSON.stringify(replacements)
// An empty replacements table records that this shell has no fallback
// params.
postponedString = `${replacementsString.length}${replacementsString}null`
const fallbackParamsString = JSON.stringify(
fallbackRouteParams ? Array.from(fallbackRouteParams.keys()) : []
)
// Record the unknown param names even when React has no HTML to resume.
// An empty array explicitly records that this shell has no fallback params.
postponedString = `${fallbackParamsString.length}${fallbackParamsString}null`
}
return serializePostponedState(
......@@ -248,7 +244,6 @@ export function parseResumeDataCacheFromPostponedState(
export function parsePostponedState(
state: string,
interpolatedParams: Params,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression = false
): PostponedState {
......@@ -275,19 +270,19 @@ export function parsePostponedState(
)
}
// This is the length of the replacements entries.
// This is the length of the serialized fallback params.
const length = parseInt(match)
const replacements = JSON.parse(
const fallbackParamNames = JSON.parse(
postponedString.slice(
match.length,
// We then go to the end of the string.
match.length + length
)
) as OpaqueFallbackRouteParamEntries
) as string[]
const stagedFallbackParams =
replacements.length > 0 ? new Map(replacements) : null
fallbackParamNames.length > 0 ? new Set(fallbackParamNames) : null
let postponed = postponedString.slice(match.length + length)
const postponed = postponedString.slice(match.length + length)
if (postponed === 'null') {
return {
type: DynamicState.DATA,
......@@ -296,29 +291,6 @@ export function parsePostponedState(
}
}
for (const [
segmentKey,
[searchValue, dynamicParamType],
] of replacements) {
const {
treeSegment: [
,
// This is the same value that'll be used in the postponed state
// as it's part of the tree data. That's why we use it as the
// replacement value.
value,
],
} = getDynamicParam(
interpolatedParams,
segmentKey,
dynamicParamType,
null,
null // staticSiblings not needed for postponed state
)
postponed = postponed.replaceAll(searchValue, value)
}
return {
type: DynamicState.HTML,
stagedFallbackParams,
......@@ -412,9 +384,8 @@ export function getPostponedFromState(state: DynamicHTMLPostponedState) {
* dynamic hole (a blocking dynamic API at the root with no Suspense boundary
* above it). Returns false for dynamic-data states or unparseable input.
*
* Unlike `parsePostponedState`, this does not interpolate fallback route params
* or build a resume data cache: it only reads the prelude marker, which is
* independent of param values. The Instant Navigation Testing API uses this to
* Unlike `parsePostponedState`, this does not build a resume data cache: it only
* reads the prelude marker. The Instant Navigation Testing API uses this to
* detect the blank-document case in both dev (fresh render) and production
* (prebuilt shell), where the marker is persisted in the postponed state.
*/
......@@ -436,16 +407,16 @@ export function isEmptyHTMLPrelude(state: string): boolean {
return false
}
// An optional `<n><replacements>` prefix carries fallback route param
// replacements; skip it to reach the `[preludeState, postponed]` data.
// An optional `<n><fallbackParams>` prefix records the unknown params;
// skip it to reach the `[preludeState, postponed]` data.
if (/^[0-9]/.test(postponedString)) {
const replacementsLengthMatch = postponedString.match(/^([0-9]*)/)?.[1]
if (!replacementsLengthMatch) {
const fallbackParamsLengthMatch = postponedString.match(/^([0-9]*)/)?.[1]
if (!fallbackParamsLengthMatch) {
return false
}
const replacementsLength = parseInt(replacementsLengthMatch)
const fallbackParamsLength = parseInt(fallbackParamsLengthMatch)
postponedString = postponedString.slice(
replacementsLengthMatch.length + replacementsLength
fallbackParamsLengthMatch.length + fallbackParamsLength
)
}
......
......@@ -102,7 +102,7 @@ export interface RequestStore extends CommonWorkUnitStore {
* These params resolve after the static stage without replacing their
* concrete values.
*/
stagedFallbackParams?: OpaqueFallbackRouteParams | null
stagedFallbackParams?: ReadonlySet<string> | null
varyParamsAccumulator?: ResponseVaryParamsAccumulator | null
// Only in build-time instant-validation or when rendering
......
......@@ -28,7 +28,6 @@ import type { ServerComponentsHmrCache } from '../response-cache'
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
/**
* Internal request headers that userland `headers()` must not expose. They stay
......@@ -146,7 +145,7 @@ export type RequestStoreInputs = {
* edit, for every client, regardless of whether it runs the HMR client.
*/
hmrRefreshHash: string | undefined
stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined
stagedFallbackParams: ReadonlySet<string> | null | undefined
}
/**
......@@ -193,7 +192,7 @@ export function createRequestStoreForRender(
isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
resumeDataCache: ResumeDataCache | null,
stagedFallbackParams: OpaqueFallbackRouteParams | null,
stagedFallbackParams: ReadonlySet<string> | null,
hmrRefreshHash: string | undefined
): RequestStore {
return createRequestStore({
......
......@@ -22,7 +22,11 @@ export function isEmptyParams(params: Params): boolean {
export function hasFallbackRouteParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
fallbackParams:
| OpaqueFallbackRouteParams
| ReadonlySet<string>
| null
| undefined
): boolean {
if (fallbackParams) {
for (let key in underlyingParams) {
......
......@@ -55,8 +55,8 @@ describe('createOpaqueFallbackRouteParams', () => {
it('get method works correctly', () => {
const result = createOpaqueFallbackRouteParams(fallbackParams)!
expect(result.get('slug')?.[0]).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
expect(result.get('modal')?.[0]).toMatch(/^%%drp:modal:[a-f0-9]+%%$/)
expect(result.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
expect(result.get('modal')).toMatch(/^%%drp:modal:[a-f0-9]+%%$/)
expect(result.get('nonexistent')).toBeUndefined()
expect(result.get('')).toBeUndefined()
})
......@@ -67,7 +67,7 @@ describe('createOpaqueFallbackRouteParams', () => {
const entries = Array.from(result.entries())
expect(entries).toHaveLength(2)
const [name, [value]] = entries[0]
const [name, value] = entries[0]
expect(name).toBe('slug')
expect(value).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
......@@ -132,7 +132,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.has('slug')).toBe(true)
expect(result!.get('slug')?.[1]).toBe('d') // 'd' = dynamic (short type)
expect(result!.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
it('should extract multiple nested dynamic segments', () => {
......@@ -149,8 +149,8 @@ describe('getFallbackRouteParams', () => {
expect(result!.size).toBe(2)
expect(result!.has('category')).toBe(true)
expect(result!.has('slug')).toBe(true)
expect(result!.get('category')?.[1]).toBe('d')
expect(result!.get('slug')?.[1]).toBe('d')
expect(result!.get('category')).toMatch(/^%%drp:category:[a-f0-9]+%%$/)
expect(result!.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
it('should extract catchall segment', () => {
......@@ -162,7 +162,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.size).toBe(1)
expect(result!.has('slug')).toBe(true)
expect(result!.get('slug')?.[1]).toBe('c') // 'c' = catchall
expect(result!.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
it('should extract optional catchall segment', () => {
......@@ -178,7 +178,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.size).toBe(1)
expect(result!.has('slug')).toBe(true)
expect(result!.get('slug')?.[1]).toBe('oc') // 'oc' = optional-catchall
expect(result!.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
it('should extract mixed static and dynamic segments', () => {
......@@ -407,8 +407,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.size).toBe(1)
expect(result!.has('photoId')).toBe(true)
// Should have intercepted type
expect(result!.get('photoId')?.[1]).toBe('di(.)') // 'di(.)' = dynamic-intercepted-(.)'
expect(result!.get('photoId')).toMatch(/^%%drp:photoId:[a-f0-9]+%%$/)
})
})
......@@ -640,7 +639,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.size).toBe(1)
expect(result!.has('slug')).toBe(true)
expect(result!.get('slug')?.[1]).toBe('c') // catchall
expect(result!.get('slug')).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
it('should handle optional catchall in parallel route', () => {
......@@ -654,7 +653,7 @@ describe('getFallbackRouteParams', () => {
expect(result).not.toBeNull()
expect(result!.size).toBe(1)
expect(result!.has('optional')).toBe(true)
expect(result!.get('optional')?.[1]).toBe('oc') // optional-catchall
expect(result!.get('optional')).toMatch(/^%%drp:optional:[a-f0-9]+%%$/)
result = getFallbackRouteParams('/sidebar/is/real', routeModule)
expect(result).toBeNull()
......
import { resolveRouteParamsFromTree } from '../../build/static-paths/utils'
import type { FallbackRouteParam } from '../../build/static-paths/types'
import type { DynamicParamTypesShort } from '../../shared/lib/app-router-types'
import { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type'
import type AppPageRouteModule from '../route-modules/app-page/module'
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'
import { getParamProperties } from '../../shared/lib/router/utils/get-segment-param'
import { InvariantError } from '../../shared/lib/invariant-error'
export type OpaqueFallbackRouteParamValue = [
/**
* The search value of the fallback route param. This is the opaque key
* that will be used to replace the dynamic param in the postponed state.
*/
searchValue: string,
/**
* The dynamic param type of the fallback route param. This is the type of
* the dynamic param that will be used to replace the dynamic param in the
* postponed state.
*/
dynamicParamType: DynamicParamTypesShort,
]
/**
* An opaque fallback route params object. This is used to store the fallback
* route params in a way that is not easily accessible to the client.
*/
export type OpaqueFallbackRouteParams = ReadonlyMap<
string,
OpaqueFallbackRouteParamValue
>
/**
* The entries of the opaque fallback route params object.
*
* @param key the key of the fallback route param
* @param value the value of the fallback route param
* Maps unknown param names to internal placeholders. The parameter wrappers
* control when reads suspend; these placeholders must not become rendered UI.
*/
export type OpaqueFallbackRouteParamEntries =
ReturnType<OpaqueFallbackRouteParams['entries']> extends MapIterator<
[infer K, infer V]
>
? ReadonlyArray<[K, V]>
: never
export type OpaqueFallbackRouteParams = ReadonlyMap<string, string>
/**
* Creates an opaque fallback route params object from the fallback route params.
......@@ -62,15 +29,12 @@ export function createOpaqueFallbackRouteParams(
// be also be unique.
const uniqueID = Math.random().toString(16).slice(2)
const keys = new Map<string, OpaqueFallbackRouteParamValue>()
const keys = new Map<string, string>()
// Generate a unique key for the fallback route param, if this key is found
// in the static output, it represents a bug in cache components.
for (const { paramName, paramType } of fallbackRouteParams) {
keys.set(paramName, [
`%%drp:${paramName}:${uniqueID}%%`,
dynamicParamTypes[paramType],
])
for (const { paramName } of fallbackRouteParams) {
keys.set(paramName, `%%drp:${paramName}:${uniqueID}%%`)
}
return keys
......@@ -196,7 +160,6 @@ export function getFallbackRouteParams(
fallbackRouteParams // Will be mutated to add route params
)
// Convert the fallback route params to an opaque format that can be safely
// used in the postponed state without exposing implementation details.
// Track the unknown params using the same opaque placeholders as prerenders.
return createOpaqueFallbackRouteParams(fallbackRouteParams)
}
......@@ -2,7 +2,6 @@ import {
workAsyncStorage,
type WorkStore,
} from '../app-render/work-async-storage.external'
import type { OpaqueFallbackRouteParams } from './fallback-params'
import type { VaryParamsAccumulator } from '../app-render/vary-params'
import {
createVaryingParams,
......@@ -663,7 +662,7 @@ function createRenderParamsInProd(userspaceParams: Params): Promise<Params> {
function createRenderParamsInDev(
underlyingParams: Params,
userpaceParams: Params,
stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined,
stagedFallbackParams: ReadonlySet<string> | null | undefined,
workStore: WorkStore,
requestStore: RequestStore
): Promise<Params> {
......
......@@ -130,7 +130,7 @@ describe('getDynamicParam', () => {
it('should handle parallel routes with fallback params for catchall', () => {
const params: Params = { category: 'electronics' }
const fallbackParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:parallel123%%', 'd'],
slug: '%%drp:slug:parallel123%%',
})
const result = getDynamicParam(params, 'slug', 'd', fallbackParams, null)
......@@ -197,7 +197,7 @@ describe('getDynamicParam', () => {
it('should use fallback param value when available', () => {
const params: Params = { slug: 'original-value' }
const fallbackParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:abc123%%', 'd'],
slug: '%%drp:slug:abc123%%',
})
const result = getDynamicParam(params, 'slug', 'd', fallbackParams, null)
......@@ -213,7 +213,7 @@ describe('getDynamicParam', () => {
it('should not encode fallback param values', () => {
const params: Params = { slug: 'hello world' }
const fallbackParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:xyz789%%', 'd'],
slug: '%%drp:slug:xyz789%%',
})
const result = getDynamicParam(params, 'slug', 'd', fallbackParams, null)
......@@ -224,7 +224,7 @@ describe('getDynamicParam', () => {
it('should use fallback params with catchall routes', () => {
const params: Params = { slug: ['docs', 'api'] }
const fallbackParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:def456%%', 'c'],
slug: '%%drp:slug:def456%%',
})
const result = getDynamicParam(params, 'slug', 'c', fallbackParams, null)
......@@ -240,7 +240,7 @@ describe('getDynamicParam', () => {
it('should use fallback params with optional catchall routes', () => {
const params: Params = {}
const fallbackParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:ghi789%%', 'oc'],
slug: '%%drp:slug:ghi789%%',
})
const result = getDynamicParam(params, 'slug', 'oc', fallbackParams, null)
......@@ -256,7 +256,7 @@ describe('getDynamicParam', () => {
it('should fall back to regular encoding when param not in fallback', () => {
const params: Params = { slug: 'hello world' }
const fallbackParams = createMockOpaqueFallbackRouteParams({
other: ['%%drp:other:abc123%%', 'd'],
other: '%%drp:other:abc123%%',
})
const result = getDynamicParam(params, 'slug', 'd', fallbackParams, null)
......
......@@ -28,8 +28,8 @@ function getParamValue(
if (fallbackRouteParams?.has(segmentKey)) {
// We know that the fallback route params has the segment key because we
// checked that above.
const [searchValue] = fallbackRouteParams.get(segmentKey)!
value = searchValue
const placeholder = fallbackRouteParams.get(segmentKey)!
value = placeholder
} else if (Array.isArray(value)) {
value = value.map((i) => encodeURIComponent(i))
} else if (typeof value === 'string') {
......
......@@ -66,7 +66,8 @@ describe('action-only fallback resume data cache', () => {
const metadata = await next.readJSON(`.next/server/app${route}.meta`)
const postponed = metadata.postponed as string
expect(postponed).toEqual(expect.any(String))
expect(postponed).toMatch(/^\d+:\d+\[\["id",/)
// Resume metadata records which params are deferred, not their placeholders.
expect(postponed).toMatch(/^\d+:\d+\["id"\]\[/)
const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json'
......
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