Unverified Commit badf4b6c authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

feat(build): add client param parsing support for PPR routes (#82621)

### What?

This PR introduces comprehensive type-aware parameter tracking and
fallback handling for dynamic routes in PPR scenarios, with enhanced
client-side parameter resolution capabilities.

### Why?

When using client segment cache with dynamic routes, Next.js faced
several critical issues that prevented reliable client-side navigation:

**1. Parameter Resolution Inconsistencies**: The previous system had
inconsistent behavior when handling parallel route parameters, causing
unpredictable parameter resolution across different route segments. This
led to client-side navigation failures when encountering dynamic route
segments that weren't statically generated.

**2. Limited Parameter Type Awareness**: The routing system lacked
semantic understanding of different parameter types (dynamic, catchall,
optional catchall), making it impossible to implement advanced parameter
handling features or provide proper fallback behavior for different
parameter scenarios.

**3. Incomplete Fallback Parameter Collection**: The original
`getFallbackRouteParams()` used simple string-based tracking that
couldn't capture the full complexity of parameter relationships,
especially in parallel route scenarios where parameters might be defined
at different levels of the route tree.

**4. Client-Side Parameter Extraction Gaps**: The `getDynamicParam`
function had limitations in handling fallback route parameters and
lacked proper encoding/decoding mechanisms, leading to potential
client-side errors during route resolution.

**5. Configuration Validation Missing**: There was no validation to
ensure `clientParamParsing` was only enabled when `clientSegmentCache`
was also enabled, leading to potential misconfigurations in production.

These issues became critical blockers for implementing reliable
client-side parameter parsing in PPR scenarios, particularly for the
Vercel platform integration
(https://github.com/vercel/vercel/pull/13740).

### How?

- Introduces `DynamicParamTypes` and `OpaqueFallbackRouteParams` for
structured, type-aware parameter tracking
- Refactors `getFallbackRouteParams()` to use route modules for
comprehensive parameter collection across the routing tree
- Adds `resolveParallelRouteParams` function to eliminate parallel route
parameter inconsistencies
- Enhances `getDynamicParam` with proper fallback parameter handling,
encoding, and comprehensive catchall support
- Implements configuration validation in `assignDefaultsAndValidate()`
to prevent misconfigurations
- Adds clientParamParsing boolean to the routes manifest configuration
(needed for https://github.com/vercel/vercel/pull/13740)
- Updates build pipeline to properly handle enhanced fallback parameters
across static generation, export, and rendering phases

NAR-305

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent 8cd4251f
...@@ -784,5 +784,12 @@ ...@@ -784,5 +784,12 @@
"783": "Expected document.currentScript to be a <script> element. Received %s instead.", "783": "Expected document.currentScript to be a <script> element. Received %s instead.",
"784": "Expected document.currentScript src to contain '/_next/'. Received %s instead.", "784": "Expected document.currentScript src to contain '/_next/'. Received %s instead.",
"785": "Expected webSocket to be defined in dev mode.", "785": "Expected webSocket to be defined in dev mode.",
"786": "Expected staticIndicatorState to be defined in dev mode." "786": "Expected staticIndicatorState to be defined in dev mode.",
"787": "\\`experimental.clientParamParsing\\` can not be \\`true\\` when \\`experimental.clientSegmentCache\\` is \\`false\\`. Client param parsing is only relevant when client segment cache is enabled.",
"788": "Unexpected dynamic param type: %s",
"789": "Expected RSC response, got %s",
"790": "Invariant: Expected RSC response, got %s",
"791": "Unexpected match for a pathname \"%s\" with a param \"%s\" of type \"%s\"",
"792": "Unexpected empty path segments match for a pathname \"%s\" with param \"%s\" of type \"%s\"",
"793": "No value found for segment key: \"%s\""
} }
...@@ -143,7 +143,7 @@ import { ...@@ -143,7 +143,7 @@ import {
collectMeta, collectMeta,
} from './utils' } from './utils'
import type { PageInfo, PageInfos } from './utils' import type { PageInfo, PageInfos } from './utils'
import type { PrerenderedRoute } from './static-paths/types' import type { FallbackRouteParam, PrerenderedRoute } from './static-paths/types'
import type { AppSegmentConfig } from './segment-config/app/app-segment-config' import type { AppSegmentConfig } from './segment-config/app/app-segment-config'
import { writeBuildId } from './write-build-id' import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
...@@ -323,6 +323,12 @@ export interface DynamicPrerenderManifestRoute { ...@@ -323,6 +323,12 @@ export interface DynamicPrerenderManifestRoute {
*/ */
fallbackRootParams: readonly string[] | undefined fallbackRootParams: readonly string[] | undefined
/**
* The fallback route params for this route that were parsed from the loader
* tree.
*/
fallbackRouteParams: readonly FallbackRouteParam[] | undefined
/** /**
* The source route that this fallback route is based on. This is a reference * The source route that this fallback route is based on. This is a reference
* so that we can associate this dynamic route with the correct source. * so that we can associate this dynamic route with the correct source.
...@@ -461,6 +467,12 @@ export type RoutesManifest = { ...@@ -461,6 +467,12 @@ export type RoutesManifest = {
prefetchSegmentHeader: typeof NEXT_ROUTER_SEGMENT_PREFETCH_HEADER prefetchSegmentHeader: typeof NEXT_ROUTER_SEGMENT_PREFETCH_HEADER
prefetchSegmentDirSuffix: typeof RSC_SEGMENTS_DIR_SUFFIX prefetchSegmentDirSuffix: typeof RSC_SEGMENTS_DIR_SUFFIX
prefetchSegmentSuffix: typeof RSC_SEGMENT_SUFFIX prefetchSegmentSuffix: typeof RSC_SEGMENT_SUFFIX
/**
* Whether the client param parsing is enabled. This is only relevant for
* app pages when PPR is enabled.
*/
clientParamParsing: boolean
} }
rewriteHeaders: { rewriteHeaders: {
pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER
...@@ -1541,6 +1553,10 @@ export default async function build( ...@@ -1541,6 +1553,10 @@ export default async function build(
prefetchSegmentHeader: NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, prefetchSegmentHeader: NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
prefetchSegmentSuffix: RSC_SEGMENT_SUFFIX, prefetchSegmentSuffix: RSC_SEGMENT_SUFFIX,
prefetchSegmentDirSuffix: RSC_SEGMENTS_DIR_SUFFIX, prefetchSegmentDirSuffix: RSC_SEGMENTS_DIR_SUFFIX,
clientParamParsing:
// NOTE: once this is the default for `clientSegmentCache`, this
// should exclusively be based on the `clientSegmentCache` flag.
config.experimental.clientParamParsing ?? false,
}, },
rewriteHeaders: { rewriteHeaders: {
pathHeader: NEXT_REWRITTEN_PATH_HEADER, pathHeader: NEXT_REWRITTEN_PATH_HEADER,
...@@ -2886,9 +2902,19 @@ export default async function build( ...@@ -2886,9 +2902,19 @@ export default async function build(
// If the route has any dynamic root segments, we need to skip // If the route has any dynamic root segments, we need to skip
// rendering the route. This is because we don't support // rendering the route. This is because we don't support
// revalidating the shells without the parameters present. // revalidating the shells without the parameters present.
// Note that we only have fallback root params if we also have
// PPR enabled for this route/app already.
if ( if (
route.fallbackRootParams && route.fallbackRootParams &&
route.fallbackRootParams.length > 0 route.fallbackRootParams.length > 0 &&
// We don't skip rendering the route if we have the
// following enabled. This is because the flight data now
// does not contain any of the route params and is instead
// completely static.
!(
config.experimental.clientSegmentCache &&
config.experimental.clientParamParsing
)
) { ) {
return return
} }
...@@ -3186,12 +3212,25 @@ export default async function build( ...@@ -3186,12 +3212,25 @@ export default async function build(
dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`) dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`)
} }
let prefetchDataRoute: string | null | undefined let prefetchDataRoute: string | null = null
// While we may only write the `.rsc` when the route does not // While we may only write the `.rsc` when the route does not
// have PPR enabled, we still want to generate the route when // have PPR enabled, we still want to generate the route when
// deployed so it doesn't 404. If the app has PPR enabled, we // deployed so it doesn't 404. If the app has PPR enabled, we
// should add this key. // should add this key.
if (!isAppRouteHandler && isAppPPREnabled) { if (
!isAppRouteHandler &&
isAppPPREnabled &&
// Don't add a prefetch data route if we have both
// clientSegmentCache and clientParamParsing enabled. This is
// because we don't actually use the prefetch data route in
// this case. This only applies if we have PPR enabled for
// this route.
!(
config.experimental.clientSegmentCache &&
config.experimental.clientParamParsing &&
isRoutePPREnabled
)
) {
prefetchDataRoute = path.posix.join( prefetchDataRoute = path.posix.join(
`${normalizedRoute}${RSC_PREFETCH_SUFFIX}` `${normalizedRoute}${RSC_PREFETCH_SUFFIX}`
) )
...@@ -3264,14 +3303,25 @@ export default async function build( ...@@ -3264,14 +3303,25 @@ export default async function build(
dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`) dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`)
} }
let prefetchDataRoute: string | undefined let prefetchDataRoute: string | null = null
let dynamicRoute = routesManifest.dynamicRoutes.find( let dynamicRoute = routesManifest.dynamicRoutes.find(
(r) => r.page === route.pathname (r) => r.page === route.pathname
) )
if (!isAppRouteHandler && isAppPPREnabled) { if (!isAppRouteHandler && isAppPPREnabled) {
prefetchDataRoute = path.posix.join( if (
`${normalizedRoute}${RSC_PREFETCH_SUFFIX}` // Don't add a prefetch data route if we have both
) // clientSegmentCache and clientParamParsing enabled. This is
// because we don't actually use the prefetch data route in
// this case. This only applies if we have PPR enabled for
// this route.
!config.experimental.clientSegmentCache ||
!config.experimental.clientParamParsing ||
!isRoutePPREnabled
) {
prefetchDataRoute = path.posix.join(
`${normalizedRoute}${RSC_PREFETCH_SUFFIX}`
)
}
// If the dynamic route wasn't found, then we need to create // If the dynamic route wasn't found, then we need to create
// it. This ensures that for each fallback shell there's an // it. This ensures that for each fallback shell there's an
...@@ -3416,9 +3466,12 @@ export default async function build( ...@@ -3416,9 +3466,12 @@ export default async function build(
fallbackRootParams: fallback fallbackRootParams: fallback
? route.fallbackRootParams ? route.fallbackRootParams
: undefined, : undefined,
fallbackSourceRoute: route.fallbackRouteParams?.length fallbackSourceRoute:
? page route.fallbackRouteParams &&
: undefined, route.fallbackRouteParams.length > 0
? page
: undefined,
fallbackRouteParams: route.fallbackRouteParams,
dataRouteRegex: !dataRoute dataRouteRegex: !dataRoute
? null ? null
: normalizeRouteRegex( : normalizeRouteRegex(
...@@ -3945,6 +3998,7 @@ export default async function build( ...@@ -3945,6 +3998,7 @@ export default async function build(
fallbackExpire: undefined, fallbackExpire: undefined,
fallbackSourceRoute: undefined, fallbackSourceRoute: undefined,
fallbackRootParams: undefined, fallbackRootParams: undefined,
fallbackRouteParams: undefined,
dataRouteRegex: normalizeRouteRegex( dataRouteRegex: normalizeRouteRegex(
getNamedRouteRegex(dataRoute, { getNamedRouteRegex(dataRoute, {
prefixRouteKeys: true, prefixRouteKeys: true,
......
...@@ -18,7 +18,9 @@ import { ...@@ -18,7 +18,9 @@ import {
type LoaderTree, type LoaderTree,
} from '../../../server/lib/app-dir-module' } from '../../../server/lib/app-dir-module'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type { RouteModule } from '../../../server/route-modules/route-module' import type { FallbackRouteParam } from '../../static-paths/types'
import { createFallbackRouteParam } from '../../static-paths/utils'
import type { DynamicParamTypes } from '../../../shared/lib/app-router-types'
type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]> type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]>
...@@ -57,11 +59,18 @@ function attach(segment: AppSegment, userland: unknown, route: string) { ...@@ -57,11 +59,18 @@ function attach(segment: AppSegment, userland: unknown, route: string) {
export type AppSegment = { export type AppSegment = {
name: string name: string
param: string | undefined paramName: string | undefined
paramType: DynamicParamTypes | undefined
filePath: string | undefined filePath: string | undefined
config: AppSegmentConfig | undefined config: AppSegmentConfig | undefined
isDynamicSegment: boolean isDynamicSegment: boolean
generateStaticParams: GenerateStaticParams | undefined generateStaticParams: GenerateStaticParams | undefined
/**
* Whether this segment is a parallel route segment or descends from a
* parallel route segment.
*/
isParallelRouteSegment: boolean | undefined
} }
/** /**
...@@ -75,27 +84,33 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) { ...@@ -75,27 +84,33 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
// to see the same segment multiple times. // to see the same segment multiple times.
const uniqueSegments = new Map<string, AppSegment>() const uniqueSegments = new Map<string, AppSegment>()
// Queue will store tuples of [loaderTree, currentSegments] // Queue will store tuples of [loaderTree, currentSegments, isParallelRouteSegment]
type QueueItem = [LoaderTree, AppSegment[]] type QueueItem = [
const queue: QueueItem[] = [[routeModule.userland.loaderTree, []]] loaderTree: LoaderTree,
currentSegments: AppSegment[],
isParallelRouteSegment: boolean,
]
const queue: QueueItem[] = [[routeModule.userland.loaderTree, [], false]]
while (queue.length > 0) { while (queue.length > 0) {
const [loaderTree, currentSegments] = queue.shift()! const [loaderTree, currentSegments, isParallelRouteSegment] = queue.shift()!
const [name, parallelRoutes] = loaderTree const [name, parallelRoutes] = loaderTree
// Process current node // Process current node
const { mod: userland, filePath } = await getLayoutOrPageModule(loaderTree) const { mod: userland, filePath } = await getLayoutOrPageModule(loaderTree)
const isClientComponent = userland && isClientReference(userland) const isClientComponent = userland && isClientReference(userland)
const param = getSegmentParam(name)?.param const { param: paramName, type: paramType } = getSegmentParam(name) ?? {}
const segment: AppSegment = { const segment: AppSegment = {
name, name,
param, paramName,
paramType,
filePath, filePath,
config: undefined, config: undefined,
isDynamicSegment: !!param, isDynamicSegment: !!paramName,
generateStaticParams: undefined, generateStaticParams: undefined,
isParallelRouteSegment,
} }
// Only server components can have app segment configurations // Only server components can have app segment configurations
...@@ -123,7 +138,13 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) { ...@@ -123,7 +138,13 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
// Add all parallel routes to the queue // Add all parallel routes to the queue
for (const parallelRouteKey in parallelRoutes) { for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey] const parallelRoute = parallelRoutes[parallelRouteKey]
queue.push([parallelRoute, updatedSegments]) queue.push([
parallelRoute,
updatedSegments,
// A parallel route segment is one that descends from a segment that is
// not children or descends from a parallel route segment.
isParallelRouteSegment || parallelRouteKey !== 'children',
])
} }
} }
...@@ -131,7 +152,7 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) { ...@@ -131,7 +152,7 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
} }
function getSegmentKey(segment: AppSegment) { function getSegmentKey(segment: AppSegment) {
return `${segment.name}-${segment.filePath ?? ''}-${segment.param ?? ''}` return `${segment.name}-${segment.filePath ?? ''}-${segment.paramName ?? ''}`
} }
/** /**
...@@ -151,16 +172,18 @@ function collectAppRouteSegments( ...@@ -151,16 +172,18 @@ function collectAppRouteSegments(
// Generate all the segments. // Generate all the segments.
const segments: AppSegment[] = parts.map((name) => { const segments: AppSegment[] = parts.map((name) => {
const param = getSegmentParam(name)?.param const { param: paramName, type: paramType } = getSegmentParam(name) ?? {}
return { return {
name, name,
param, paramName,
paramType,
filePath: undefined, filePath: undefined,
isDynamicSegment: !!param, isDynamicSegment: !!paramName,
config: undefined, config: undefined,
generateStaticParams: undefined, generateStaticParams: undefined,
} isParallelRouteSegment: undefined,
} satisfies AppSegment
}) })
// We know we have at least one, we verified this above. We should get the // We know we have at least one, we verified this above. We should get the
...@@ -182,7 +205,7 @@ function collectAppRouteSegments( ...@@ -182,7 +205,7 @@ function collectAppRouteSegments(
* @returns the segments for the route module * @returns the segments for the route module
*/ */
export function collectSegments( export function collectSegments(
routeModule: RouteModule routeModule: AppRouteRouteModule | AppPageRouteModule
): Promise<AppSegment[]> | AppSegment[] { ): Promise<AppSegment[]> | AppSegment[] {
if (isAppRouteRouteModule(routeModule)) { if (isAppRouteRouteModule(routeModule)) {
return collectAppRouteSegments(routeModule) return collectAppRouteSegments(routeModule)
...@@ -196,3 +219,55 @@ export function collectSegments( ...@@ -196,3 +219,55 @@ export function collectSegments(
'Expected a route module to be one of app route or page' 'Expected a route module to be one of app route or page'
) )
} }
/**
* Collects the fallback route params for a given app page route module. This is
* a variant of the `collectSegments` function that only collects the fallback
* route params without importing anything.
*
* @param routeModule the app page route module
* @returns the fallback route params for the app page route module
*/
export function collectFallbackRouteParams(
routeModule: AppPageRouteModule
): readonly FallbackRouteParam[] {
const uniqueSegments = new Map<string, FallbackRouteParam>()
// Queue will store tuples of [loaderTree, isParallelRouteSegment]
type QueueItem = [loaderTree: LoaderTree, isParallelRouteSegment: boolean]
const queue: QueueItem[] = [[routeModule.userland.loaderTree, false]]
while (queue.length > 0) {
const [loaderTree, isParallelRouteSegment] = queue.shift()!
const [name, parallelRoutes] = loaderTree
// Handle this segment (if it's a dynamic segment param).
const segmentParam = getSegmentParam(name)
if (segmentParam) {
const key = `${name}-${segmentParam.param}`
if (!uniqueSegments.has(key)) {
uniqueSegments.set(
key,
createFallbackRouteParam(
segmentParam.param,
segmentParam.type,
isParallelRouteSegment
)
)
}
}
// Add all of this segment's parallel routes to the queue.
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
queue.push([
parallelRoute,
// A parallel route segment is one that descends from a segment that is
// not children or descends from a parallel route segment.
isParallelRouteSegment || parallelRouteKey !== 'children',
])
}
}
return Array.from(uniqueSegments.values())
}
This diff is collapsed.
import type { FallbackMode } from '../../lib/fallback' import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
type StaticPrerenderedRoute = { type StaticPrerenderedRoute = {
readonly params: Params readonly params: Params
...@@ -16,11 +17,34 @@ type StaticPrerenderedRoute = { ...@@ -16,11 +17,34 @@ type StaticPrerenderedRoute = {
throwOnEmptyStaticShell: undefined throwOnEmptyStaticShell: undefined
} }
export type FallbackRouteParam = {
/**
* The name of the param.
*/
readonly paramName: string
/**
* The type of the param.
*/
readonly paramType: DynamicParamTypes
/**
* Whether this is a parallel route param or descends from a parallel route
* param.
*/
readonly isParallelRouteParam: boolean
}
type FallbackPrerenderedRoute = { type FallbackPrerenderedRoute = {
readonly params: Params readonly params: Params
readonly pathname: string readonly pathname: string
readonly encodedPathname: string readonly encodedPathname: string
readonly fallbackRouteParams: readonly string[]
/**
* The fallback route params for the route. This includes both the parallel
* route params and the non-parallel route params.
*/
readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[] readonly fallbackRootParams: readonly string[]
......
import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
import type { FallbackRouteParam } from './types'
/** /**
* Encodes a parameter value using the provided encoder. * Encodes a parameter value using the provided encoder.
* *
...@@ -28,3 +31,19 @@ export function encodeParam( ...@@ -28,3 +31,19 @@ export function encodeParam(
export function normalizePathname(pathname: string) { export function normalizePathname(pathname: string) {
return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '') return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '')
} }
/**
* Creates a fallback route param.
*
* @param paramName - The name of the param.
* @param isParallelRouteParam - Whether this is a parallel route param or
* descends from a parallel route param.
* @returns The fallback route param.
*/
export function createFallbackRouteParam(
paramName: string,
paramType: DynamicParamTypes,
isParallelRouteParam: boolean
): FallbackRouteParam {
return { paramName, paramType, isParallelRouteParam }
}
...@@ -18,7 +18,8 @@ import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' ...@@ -18,7 +18,8 @@ import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { import {
getFallbackRouteParams, getFallbackRouteParams,
type FallbackRouteParams, createOpaqueFallbackRouteParams,
type OpaqueFallbackRouteParams,
} from '../../server/request/fallback-params' } from '../../server/request/fallback-params'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils' import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'
import { import {
...@@ -89,6 +90,7 @@ export const __next_app__ = { ...@@ -89,6 +90,7 @@ export const __next_app__ = {
import * as entryBase from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' } import * as entryBase from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
import { RedirectStatusCode } from '../../client/components/redirect-status-code' import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { InvariantError } from '../../shared/lib/invariant-error'
export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' } export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
...@@ -447,7 +449,7 @@ export async function handler( ...@@ -447,7 +449,7 @@ export async function handler(
/** /**
* The unknown route params for this render. * The unknown route params for this render.
*/ */
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
}): Promise<ResponseCacheEntry> => { }): Promise<ResponseCacheEntry> => {
const context: AppPageRouteHandlerContext = { const context: AppPageRouteHandlerContext = {
query, query,
...@@ -515,7 +517,9 @@ export async function handler( ...@@ -515,7 +517,9 @@ export async function handler(
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
serverActions: nextConfig.experimental.serverActions, serverActions: nextConfig.experimental.serverActions,
...(isDebugStaticShell || isDebugDynamicAccesses ...(isDebugStaticShell ||
isDebugDynamicAccesses ||
isDebugFallbackShell
? { ? {
nextExport: true, nextExport: true,
supportsDynamicResponse: false, supportsDynamicResponse: false,
...@@ -697,19 +701,38 @@ export async function handler( ...@@ -697,19 +701,38 @@ export async function handler(
throw new NoFallbackError() throw new NoFallbackError()
} }
let fallbackResponse: ResponseCacheEntry | null | undefined // When client param parsing is enabled, we can use the fallback
// response if the request is not a dynamic RSC request because the
if (isRoutePPREnabled && !isRSCRequest) { // RSC data when this feature flag is enabled does not contain any
// param references. Without this feature flag enabled, the RSC data
// contains param references, and therefore we can't use the fallback.
if (
isRoutePPREnabled &&
(nextConfig.experimental.clientParamParsing
? !isDynamicRSCRequest
: !isRSCRequest)
) {
const cacheKey = const cacheKey =
typeof prerenderInfo?.fallback === 'string' isProduction && typeof prerenderInfo?.fallback === 'string'
? prerenderInfo.fallback ? prerenderInfo.fallback
: isProduction : normalizedSrcPage
? normalizedSrcPage
const fallbackRouteParams =
// If we're in production and we have fallback route params, then we
// can use the manifest fallback route params.
isProduction && prerenderInfo?.fallbackRouteParams
? createOpaqueFallbackRouteParams(
prerenderInfo.fallbackRouteParams
)
: // Otherwise, if we're debugging the fallback shell, then we
// have to manually generate the fallback route params.
isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null : null
// We use the response cache here to handle the revalidation and // We use the response cache here to handle the revalidation and
// management of the fallback shell. // management of the fallback shell.
fallbackResponse = await routeModule.handleResponse({ const fallbackResponse = await routeModule.handleResponse({
cacheKey, cacheKey,
req, req,
nextConfig, nextConfig,
...@@ -723,13 +746,7 @@ export async function handler( ...@@ -723,13 +746,7 @@ export async function handler(
// We pass `undefined` as rendering a fallback isn't resumed // We pass `undefined` as rendering a fallback isn't resumed
// here. // here.
postponed: undefined, postponed: undefined,
fallbackRouteParams: fallbackRouteParams,
// If we're in production or we're debugging the fallback
// shell then we should postpone when dynamic params are
// accessed.
isProduction || isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage)
: null,
}), }),
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
}) })
...@@ -747,6 +764,7 @@ export async function handler( ...@@ -747,6 +764,7 @@ export async function handler(
} }
} }
} }
// Only requests that aren't revalidating can be resumed. If we have the // Only requests that aren't revalidating can be resumed. If we have the
// minimal postponed data, then we should resume the render with it. // minimal postponed data, then we should resume the render with it.
const postponed = const postponed =
...@@ -772,15 +790,19 @@ export async function handler( ...@@ -772,15 +790,19 @@ export async function handler(
} }
} }
// If this is a dynamic route with PPR enabled and the default route
// matches were set, then we should pass the fallback route params to
// the renderer as this is a fallback revalidation request.
const fallbackRouteParams = const fallbackRouteParams =
pageIsDynamic && // If we're in production and we have fallback route params, then we
isRoutePPREnabled && // can use the manifest fallback route params if we need to render the
(getRequestMeta(req, 'renderFallbackShell') || isDebugFallbackShell) // fallback shell.
? getFallbackRouteParams(pathname) isProduction &&
: null prerenderInfo?.fallbackRouteParams &&
getRequestMeta(req, 'renderFallbackShell')
? createOpaqueFallbackRouteParams(prerenderInfo.fallbackRouteParams)
: // Otherwise, if we're debugging the fallback shell, then we have to
// manually generate the fallback route params.
isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
// Perform the render. // Perform the render.
return doRender({ return doRender({
...@@ -1071,8 +1093,26 @@ export async function handler( ...@@ -1071,8 +1093,26 @@ export async function handler(
if (isRSCRequest && !isDraftMode) { if (isRSCRequest && !isDraftMode) {
// If this is a dynamic RSC request, then stream the response. // If this is a dynamic RSC request, then stream the response.
if (typeof cachedData.rscData === 'undefined') { if (typeof cachedData.rscData === 'undefined') {
if (cachedData.postponed) { // If the response is not an RSC response, then we can't serve it.
throw new Error('Invariant: Expected postponed to be undefined') if (cachedData.html.contentType !== RSC_CONTENT_TYPE_HEADER) {
if (nextConfig.experimental.clientParamParsing) {
// If client param parsing is enabled, then we can return a 404.
// This was likely an old prefetch request.
res.statusCode = 404
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl,
})
} else {
// Otherwise this case is not expected.
throw new InvariantError(
`Expected RSC response, got ${cachedData.html.contentType}`
)
}
} }
return sendRenderResult({ return sendRenderResult({
......
...@@ -15,7 +15,10 @@ import type { ...@@ -15,7 +15,10 @@ import type {
MiddlewareManifest, MiddlewareManifest,
} from './webpack/plugins/middleware-plugin' } from './webpack/plugins/middleware-plugin'
import type { WebpackLayerName } from '../lib/constants' import type { WebpackLayerName } from '../lib/constants'
import type { AppPageModule } from '../server/route-modules/app-page/module' import type {
AppPageModule,
AppPageRouteModule,
} from '../server/route-modules/app-page/module'
import type { NextComponentType } from '../shared/lib/utils' import type { NextComponentType } from '../shared/lib/utils'
import '../server/require-hook' import '../server/require-hook'
...@@ -83,6 +86,7 @@ import { buildPagesStaticPaths } from './static-paths/pages' ...@@ -83,6 +86,7 @@ import { buildPagesStaticPaths } from './static-paths/pages'
import type { PrerenderedRoute } from './static-paths/types' import type { PrerenderedRoute } from './static-paths/types'
import type { CacheControl } from '../server/lib/cache-control' import type { CacheControl } from '../server/lib/cache-control'
import { formatExpire, formatRevalidate } from './output/format' import { formatExpire, formatRevalidate } from './output/format'
import type { AppRouteRouteModule } from '../server/route-modules/app-route/module'
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -1174,9 +1178,13 @@ export async function isPageStatic({ ...@@ -1174,9 +1178,13 @@ export async function isPageStatic({
isClientComponent = isClientReference(componentsResult.ComponentMod) isClientComponent = isClientReference(componentsResult.ComponentMod)
let segments let segments: AppSegment[]
try { try {
segments = await collectSegments(routeModule) segments = 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
)
} catch (err) { } catch (err) {
throw new Error(`Failed to collect configuration for ${page}`, { throw new Error(`Failed to collect configuration for ${page}`, {
cause: err, cause: err,
......
...@@ -2,8 +2,9 @@ import { useContext } from 'react' ...@@ -2,8 +2,9 @@ import { useContext } from 'react'
import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime' import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'
/** /**
* This checks to see if the current render has any unknown route parameters. * This checks to see if the current render has any unknown route parameters that
* It's used to trigger a different render path in the error boundary. * would cause the pathname to be dynamic. It's used to trigger a different
* render path in the error boundary.
* *
* @returns true if there are any unknown route parameters, false otherwise * @returns true if there are any unknown route parameters, false otherwise
*/ */
......
...@@ -24,7 +24,7 @@ import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' ...@@ -24,7 +24,7 @@ import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers' import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers'
import type { FetchMetrics } from '../../server/base-http' import type { FetchMetrics } from '../../server/base-http'
import type { WorkStore } from '../../server/app-render/work-async-storage.external' import type { WorkStore } from '../../server/app-render/work-async-storage.external'
import type { FallbackRouteParams } from '../../server/request/fallback-params' import type { OpaqueFallbackRouteParams } from '../../server/request/fallback-params'
import { AfterRunner } from '../../server/after/run-with-after' import { AfterRunner } from '../../server/after/run-with-after'
import type { RequestLifecycleOpts } from '../../server/base-server' import type { RequestLifecycleOpts } from '../../server/base-server'
import type { AppSharedContext } from '../../server/app-render/app-render' import type { AppSharedContext } from '../../server/app-render/app-render'
...@@ -45,7 +45,7 @@ export async function exportAppPage( ...@@ -45,7 +45,7 @@ export async function exportAppPage(
path: string, path: string,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
fallbackRouteParams: FallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>, partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>,
htmlFilepath: string, htmlFilepath: string,
debugOutput: boolean, debugOutput: boolean,
...@@ -132,14 +132,19 @@ export async function exportAppPage( ...@@ -132,14 +132,19 @@ export async function exportAppPage(
// If page data isn't available, it means that the page couldn't be rendered // If page data isn't available, it means that the page couldn't be rendered
// properly so long as we don't have unknown route params. When a route doesn't // properly so long as we don't have unknown route params. When a route doesn't
// have unknown route params, there will not be any flight data. // have unknown route params, there will not be any flight data.
if ( if (!flightData) {
!flightData && // Unless the user has clientParamParsing enabled, we expect that routes
(!fallbackRouteParams || fallbackRouteParams.size === 0) // that don't have fallback route params would have flight data. This is
) { // because when clientParamParsing is enabled, the absence of flight data
throw new Error(`Invariant: failed to get page data for ${path}`) // means that the route has unknown route params.
} if (
!fallbackRouteParams ||
if (flightData) { fallbackRouteParams.size === 0 ||
renderOpts.experimental.clientParamParsing
) {
throw new Error(`Invariant: failed to get page data for ${path}`)
}
} else {
// If PPR is enabled, we want to emit a prefetch rsc file for the page // If PPR is enabled, we want to emit a prefetch rsc file for the page
// instead of the standard rsc. This is because the standard rsc will // instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data. We do this if any routes have PPR enabled so // contain the dynamic data. We do this if any routes have PPR enabled so
......
...@@ -40,8 +40,8 @@ import { ...@@ -40,8 +40,8 @@ import {
} from '../build/turborepo-access-trace' } from '../build/turborepo-access-trace'
import type { Params } from '../server/request/params' import type { Params } from '../server/request/params'
import { import {
getFallbackRouteParams, createOpaqueFallbackRouteParams,
type FallbackRouteParams, type OpaqueFallbackRouteParams,
} from '../server/request/fallback-params' } from '../server/request/fallback-params'
import { needsExperimentalReact } from '../lib/needs-experimental-react' import { needsExperimentalReact } from '../lib/needs-experimental-react'
import type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled' import type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'
...@@ -119,8 +119,8 @@ async function exportPageImpl( ...@@ -119,8 +119,8 @@ async function exportPageImpl(
query: originalQuery = {}, query: originalQuery = {},
} = exportPath } = exportPath
const fallbackRouteParams: FallbackRouteParams | null = const fallbackRouteParams: OpaqueFallbackRouteParams | null =
getFallbackRouteParams(_fallbackRouteParams) createOpaqueFallbackRouteParams(_fallbackRouteParams)
let query = { ...originalQuery } let query = { ...originalQuery }
const pathname = normalizeAppPath(page) const pathname = normalizeAppPath(page)
......
...@@ -153,7 +153,7 @@ import { createInitialRouterState } from '../../client/components/router-reducer ...@@ -153,7 +153,7 @@ import { createInitialRouterState } from '../../client/components/router-reducer
import { createMutableActionQueue } from '../../client/components/app-router-instance' import { createMutableActionQueue } from '../../client/components/app-router-instance'
import { getRevalidateReason } from '../instrumentation/utils' import { getRevalidateReason } from '../instrumentation/utils'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { FallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import { import {
prerenderAndAbortInSequentialTasksWithStages, prerenderAndAbortInSequentialTasksWithStages,
processPrelude, processPrelude,
...@@ -365,7 +365,7 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -365,7 +365,7 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
function makeGetDynamicParamFromSegment( function makeGetDynamicParamFromSegment(
params: { [key: string]: any }, params: { [key: string]: any },
pagePath: string, pagePath: string,
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
): GetDynamicParamFromSegment { ): GetDynamicParamFromSegment {
return function getDynamicParamFromSegment( return function getDynamicParamFromSegment(
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -1444,7 +1444,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1444,7 +1444,7 @@ async function renderToHTMLOrFlightImpl(
postponedState: PostponedState | null, postponedState: PostponedState | null,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined, serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext, sharedContext: AppSharedContext,
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
) { ) {
const isNotFoundPath = pagePath === '/404' const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) { if (isNotFoundPath) {
...@@ -1927,7 +1927,7 @@ export type AppPageRender = ( ...@@ -1927,7 +1927,7 @@ export type AppPageRender = (
res: BaseNextResponse, res: BaseNextResponse,
pagePath: string, pagePath: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
fallbackRouteParams: FallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
renderOpts: RenderOpts, renderOpts: RenderOpts,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined, serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
isDevWarmup: boolean, isDevWarmup: boolean,
...@@ -1974,6 +1974,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1974,6 +1974,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
postponedState = parsePostponedState( postponedState = parsePostponedState(
renderOpts.postponed, renderOpts.postponed,
pagePath,
renderOpts.params renderOpts.params
) )
} }
...@@ -2072,7 +2073,7 @@ async function renderToStream( ...@@ -2072,7 +2073,7 @@ async function renderToStream(
formState: any, formState: any,
postponedState: PostponedState | null, postponedState: PostponedState | null,
metadata: AppPageRenderResultMetadata, metadata: AppPageRenderResultMetadata,
devValidatingFallbackParams: FallbackRouteParams | null devValidatingFallbackParams: OpaqueFallbackRouteParams | null
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
const { assetPrefix, nonce, pagePath, renderOpts } = ctx const { assetPrefix, nonce, pagePath, renderOpts } = ctx
...@@ -2581,7 +2582,7 @@ async function spawnDynamicValidationInDev( ...@@ -2581,7 +2582,7 @@ async function spawnDynamicValidationInDev(
isNotFound: boolean, isNotFound: boolean,
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>, clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
requestStore: RequestStore, requestStore: RequestStore,
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
): Promise<void> { ): Promise<void> {
const { const {
componentMod: ComponentMod, componentMod: ComponentMod,
...@@ -3193,7 +3194,7 @@ async function prerenderToStream( ...@@ -3193,7 +3194,7 @@ async function prerenderToStream(
ctx: AppRenderContext, ctx: AppRenderContext,
metadata: AppPageRenderResultMetadata, metadata: AppPageRenderResultMetadata,
tree: LoaderTree, tree: LoaderTree,
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
): Promise<PrerenderToStreamResult> { ): Promise<PrerenderToStreamResult> {
// When prerendering formState is always null. We still include it // When prerendering formState is always null. We still include it
// because some shared APIs expect a formState value and this is slightly // because some shared APIs expect a formState value and this is slightly
......
...@@ -595,6 +595,7 @@ export function useDynamicRouteParams(expression: string) { ...@@ -595,6 +595,7 @@ export function useDynamicRouteParams(expression: string) {
case 'prerender-client': case 'prerender-client':
case 'prerender': { case 'prerender': {
const fallbackParams = workUnitStore.fallbackRouteParams const fallbackParams = workUnitStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) { if (fallbackParams && fallbackParams.size > 0) {
// We are in a prerender with cacheComponents semantics. We are going to // We are in a prerender with cacheComponents semantics. We are going to
// hang here and never resolve. This will cause the currently // hang here and never resolve. This will cause the currently
......
...@@ -13,16 +13,3 @@ export const dynamicParamTypes: Record< ...@@ -13,16 +13,3 @@ export const dynamicParamTypes: Record<
dynamic: 'd', dynamic: 'd',
'dynamic-intercepted': 'di', 'dynamic-intercepted': 'di',
} }
/**
* Shorten the dynamic param in order to make it smaller when transmitted to the browser.
*/
export function getShortDynamicParamType(
type: DynamicParamTypes
): DynamicParamTypesShort {
const short = dynamicParamTypes[type]
if (!short) {
throw new Error('Unknown dynamic param type')
}
return short
}
...@@ -10,11 +10,23 @@ import { ...@@ -10,11 +10,23 @@ import {
parsePostponedState, parsePostponedState,
DynamicHTMLPreludeState, DynamicHTMLPreludeState,
} from './postponed-state' } from './postponed-state'
import type {
OpaqueFallbackRouteParams,
OpaqueFallbackRouteParamValue,
} from '../request/fallback-params'
export function createMockOpaqueFallbackRouteParams(
params: Record<string, OpaqueFallbackRouteParamValue>
): OpaqueFallbackRouteParams {
return new Map(Object.entries(params))
}
describe('getDynamicHTMLPostponedState', () => { describe('getDynamicHTMLPostponedState', () => {
it('serializes a HTML postponed state with fallback params', async () => { it('serializes a HTML postponed state with fallback params', async () => {
const key = '%%drp:slug:e9615126684e5%%' const key = '%%drp:slug:e9615126684e5%%'
const fallbackRouteParams = new Map([['slug', key]]) const fallbackRouteParams = createMockOpaqueFallbackRouteParams({
slug: [key, 'd'],
})
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
prerenderResumeDataCache.cache.set( prerenderResumeDataCache.cache.set(
...@@ -36,7 +48,7 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -36,7 +48,7 @@ describe('getDynamicHTMLPostponedState', () => {
prerenderResumeDataCache prerenderResumeDataCache
) )
const parsed = parsePostponedState(state, { slug: '123' }) const parsed = parsePostponedState(state, '/blog/[slug]', { slug: '123' })
expect(parsed).toMatchInlineSnapshot(` expect(parsed).toMatchInlineSnapshot(`
{ {
"data": [ "data": [
...@@ -79,7 +91,9 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -79,7 +91,9 @@ describe('getDynamicHTMLPostponedState', () => {
it('can serialize and deserialize a HTML postponed state with fallback params', async () => { it('can serialize and deserialize a HTML postponed state with fallback params', async () => {
const key = '%%drp:slug:e9615126684e5%%' const key = '%%drp:slug:e9615126684e5%%'
const fallbackRouteParams = new Map([['slug', key]]) const fallbackRouteParams = createMockOpaqueFallbackRouteParams({
slug: [key, 'd'],
})
const state = await getDynamicHTMLPostponedState( const state = await getDynamicHTMLPostponedState(
{ [key]: key }, { [key]: key },
DynamicHTMLPreludeState.Full, DynamicHTMLPreludeState.Full,
...@@ -89,7 +103,7 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -89,7 +103,7 @@ describe('getDynamicHTMLPostponedState', () => {
const value = 'hello' const value = 'hello'
const params = { slug: value } const params = { slug: value }
const parsed = parsePostponedState(state, params) const parsed = parsePostponedState(state, '/blog/[slug]', params)
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.HTML,
data: [1, { [value]: value }], data: [1, { [value]: value }],
...@@ -116,7 +130,7 @@ describe('parsePostponedState', () => { ...@@ -116,7 +130,7 @@ describe('parsePostponedState', () => {
const params = { const params = {
slug: Math.random().toString(16).slice(3), slug: Math.random().toString(16).slice(3),
} }
const parsed = parsePostponedState(state, params) const parsed = parsePostponedState(state, '/blog/[slug]', params)
// Ensure that it parsed it correctly. // Ensure that it parsed it correctly.
expect(parsed).toEqual({ expect(parsed).toEqual({
...@@ -132,7 +146,7 @@ describe('parsePostponedState', () => { ...@@ -132,7 +146,7 @@ describe('parsePostponedState', () => {
it('parses a HTML postponed state without fallback params', () => { it('parses a HTML postponed state without fallback params', () => {
const state = `2:{}null` const state = `2:{}null`
const params = {} const params = {}
const parsed = parsePostponedState(state, params) const parsed = parsePostponedState(state, '/blog', params)
// Ensure that it parsed it correctly. // Ensure that it parsed it correctly.
expect(parsed).toEqual({ expect(parsed).toEqual({
...@@ -144,7 +158,7 @@ describe('parsePostponedState', () => { ...@@ -144,7 +158,7 @@ describe('parsePostponedState', () => {
it('parses a data postponed state', () => { it('parses a data postponed state', () => {
const state = '4:nullnull' const state = '4:nullnull'
const parsed = parsePostponedState(state, undefined) const parsed = parsePostponedState(state, '/blog', undefined)
// Ensure that it parsed it correctly. // Ensure that it parsed it correctly.
expect(parsed).toEqual({ expect(parsed).toEqual({
......
import type { FallbackRouteParams } from '../../server/request/fallback-params' 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 { Params } from '../request/params'
import { import {
createPrerenderResumeDataCache, createPrerenderResumeDataCache,
...@@ -74,12 +78,14 @@ export type PostponedState = ...@@ -74,12 +78,14 @@ export type PostponedState =
export async function getDynamicHTMLPostponedState( export async function getDynamicHTMLPostponedState(
postponed: ReactPostponed, postponed: ReactPostponed,
preludeState: DynamicHTMLPreludeState, preludeState: DynamicHTMLPreludeState,
fallbackRouteParams: FallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
): Promise<string> { ): Promise<string> {
const data: DynamicHTMLPostponedState['data'] = [preludeState, postponed] const data: DynamicHTMLPostponedState['data'] = [preludeState, postponed]
const dataString = JSON.stringify(data) const dataString = JSON.stringify(data)
// If there are no fallback route params, we can just serialize the postponed
// state as is.
if (!fallbackRouteParams || fallbackRouteParams.size === 0) { if (!fallbackRouteParams || fallbackRouteParams.size === 0) {
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>` // Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return `${dataString.length}:${dataString}${await stringifyResumeDataCache( return `${dataString.length}:${dataString}${await stringifyResumeDataCache(
...@@ -87,7 +93,9 @@ export async function getDynamicHTMLPostponedState( ...@@ -87,7 +93,9 @@ export async function getDynamicHTMLPostponedState(
)}` )}`
} }
const replacements: Array<[string, string]> = Array.from(fallbackRouteParams) const replacements: OpaqueFallbackRouteParamEntries = Array.from(
fallbackRouteParams.entries()
)
const replacementsString = JSON.stringify(replacements) const replacementsString = JSON.stringify(replacements)
// Serialized as `<replacements.length><replacements><data>` // Serialized as `<replacements.length><replacements><data>`
...@@ -105,6 +113,7 @@ export async function getDynamicDataPostponedState( ...@@ -105,6 +113,7 @@ export async function getDynamicDataPostponedState(
export function parsePostponedState( export function parsePostponedState(
state: string, state: string,
pagePath: string,
params: Params | undefined params: Params | undefined
): PostponedState { ): PostponedState {
try { try {
...@@ -147,13 +156,27 @@ export function parsePostponedState( ...@@ -147,13 +156,27 @@ export function parsePostponedState(
// We then go to the end of the string. // We then go to the end of the string.
match.length + length match.length + length
) )
) as ReadonlyArray<[string, string]> ) as OpaqueFallbackRouteParamEntries
let postponed = postponedString.slice(match.length + length) let postponed = postponedString.slice(match.length + length)
for (const [key, searchValue] of replacements) { for (const [key, [searchValue, dynamicParamType]] of replacements) {
const value = params?.[key] ?? '' const {
const replaceValue = Array.isArray(value) ? value.join('/') : value treeSegment: [
postponed = postponed.replaceAll(searchValue, replaceValue) ,
// 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(
params ?? {},
key,
dynamicParamType,
pagePath,
null
)
postponed = postponed.replaceAll(searchValue, value)
} }
return { return {
......
...@@ -5,7 +5,7 @@ import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers' ...@@ -5,7 +5,7 @@ import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies' import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
import type { CacheSignal } from './cache-signal' import type { CacheSignal } from './cache-signal'
import type { DynamicTrackingState } from './dynamic-rendering' import type { DynamicTrackingState } from './dynamic-rendering'
import type { FallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
// Share the instance module in the next-shared layer // Share the instance module in the next-shared layer
import { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' } import { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
...@@ -68,7 +68,7 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -68,7 +68,7 @@ export interface RequestStore extends CommonWorkUnitStore {
// DEV-only // DEV-only
usedDynamic?: boolean usedDynamic?: boolean
prerenderPhase?: boolean prerenderPhase?: boolean
devFallbackParams?: FallbackRouteParams | null devFallbackParams?: OpaqueFallbackRouteParams | null
} }
/** /**
...@@ -203,7 +203,7 @@ interface StaticPrerenderStoreCommon { ...@@ -203,7 +203,7 @@ interface StaticPrerenderStoreCommon {
* The set of unknown route parameters. Accessing these will be tracked as * The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access. * a dynamic access.
*/ */
readonly fallbackRouteParams: FallbackRouteParams | null readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/** /**
* When true, the page is prerendered as a fallback shell, while allowing any * When true, the page is prerendered as a fallback shell, while allowing any
...@@ -225,7 +225,7 @@ export interface PrerenderStorePPR ...@@ -225,7 +225,7 @@ export interface PrerenderStorePPR
* The set of unknown route parameters. Accessing these will be tracked as * The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access. * a dynamic access.
*/ */
readonly fallbackRouteParams: FallbackRouteParams | null readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/** /**
* The resume data cache for this prerender. * The resume data cache for this prerender.
......
...@@ -24,7 +24,7 @@ import type { ServerComponentsHmrCache } from '../response-cache' ...@@ -24,7 +24,7 @@ import type { ServerComponentsHmrCache } from '../response-cache'
import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache' import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/params' import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags' import type { ImplicitTags } from '../lib/implicit-tags'
import type { FallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders { function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const cleaned = HeadersAdapter.from(headers) const cleaned = HeadersAdapter.from(headers)
...@@ -116,7 +116,7 @@ export function createRequestStoreForRender( ...@@ -116,7 +116,7 @@ export function createRequestStoreForRender(
isHmrRefresh: RequestContext['isHmrRefresh'], isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'], serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
renderResumeDataCache: RenderResumeDataCache | undefined, renderResumeDataCache: RenderResumeDataCache | undefined,
devFallbackParams: FallbackRouteParams | null devFallbackParams: OpaqueFallbackRouteParams | null
): RequestStore { ): RequestStore {
return createRequestStoreImpl( return createRequestStoreImpl(
// Pages start in render phase by default // Pages start in render phase by default
...@@ -171,7 +171,7 @@ function createRequestStoreImpl( ...@@ -171,7 +171,7 @@ function createRequestStoreImpl(
previewProps: WrapperRenderOpts['previewProps'], previewProps: WrapperRenderOpts['previewProps'],
isHmrRefresh: RequestContext['isHmrRefresh'], isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'], serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
devFallbackParams: FallbackRouteParams | null | undefined devFallbackParams: OpaqueFallbackRouteParams | null | undefined
): RequestStore { ): RequestStore {
function defaultOnUpdateCookies(cookies: string[]) { function defaultOnUpdateCookies(cookies: string[]) {
if (res) { if (res) {
......
...@@ -147,6 +147,7 @@ import { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache ...@@ -147,6 +147,7 @@ import { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param' import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
import type { PrerenderedRoute } from '../build/static-paths/types' import type { PrerenderedRoute } from '../build/static-paths/types'
import { createOpaqueFallbackRouteParams } from './request/fallback-params'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -2319,13 +2320,10 @@ export default abstract class Server< ...@@ -2319,13 +2320,10 @@ export default abstract class Server<
} }
} }
if (smallestFallbackRouteParams) { if (smallestFallbackRouteParams) {
const devValidatingFallbackParams = new Map<string, string>(
smallestFallbackRouteParams.map((v) => [v, ''])
)
addRequestMeta( addRequestMeta(
req, req,
'devValidatingFallbackParams', 'devValidatingFallbackParams',
devValidatingFallbackParams createOpaqueFallbackRouteParams(smallestFallbackRouteParams)!
) )
} }
} }
......
...@@ -37,8 +37,9 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record( ...@@ -37,8 +37,9 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
z.object({ z.object({
page: z.string(), page: z.string(),
query: z.any(), // NextParsedUrlQuery query: z.any(), // NextParsedUrlQuery
// private optional properties // private optional properties
_fallbackRouteParams: z.array(z.string()).optional(), _fallbackRouteParams: z.array(z.any()).optional(),
_isAppDir: z.boolean().optional(), _isAppDir: z.boolean().optional(),
_isDynamicError: z.boolean().optional(), _isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(), _isRoutePPREnabled: z.boolean().optional(),
......
...@@ -29,6 +29,7 @@ import type { RenderingMode } from '../build/rendering-mode' ...@@ -29,6 +29,7 @@ import type { RenderingMode } from '../build/rendering-mode'
import type { Revalidate } from './lib/cache-control' import type { Revalidate } from './lib/cache-control'
import type { AdapterOutputType } from '../shared/lib/constants' import type { AdapterOutputType } from '../shared/lib/constants'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info' import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { FallbackRouteParam } from '../build/static-paths/types'
export type NextConfigComplete = Required<NextConfig> & { export type NextConfigComplete = Required<NextConfig> & {
images: Required<ImageConfigComplete> images: Required<ImageConfigComplete>
...@@ -940,7 +941,7 @@ export type ExportPathMap = { ...@@ -940,7 +941,7 @@ export type ExportPathMap = {
* *
* @internal * @internal
*/ */
_fallbackRouteParams?: readonly string[] _fallbackRouteParams?: readonly FallbackRouteParam[]
/** /**
* @internal * @internal
......
...@@ -224,7 +224,15 @@ function warnCustomizedOption( ...@@ -224,7 +224,15 @@ function warnCustomizedOption(
} }
} }
function assignDefaults( /**
* Assigns defaults to the user config and validates the config.
*
* @param dir - The directory of the project.
* @param userConfig - The user config.
* @param silent - Whether to suppress warnings.
* @returns The complete config.
*/
function assignDefaultsAndValidate(
dir: string, dir: string,
userConfig: NextConfig & { configFileName: string }, userConfig: NextConfig & { configFileName: string },
silent: boolean silent: boolean
...@@ -1173,6 +1181,18 @@ function assignDefaults( ...@@ -1173,6 +1181,18 @@ function assignDefaults(
result.experimental.ppr = true result.experimental.ppr = true
} }
// We require clientSegmentCache to be enabled if clientParamParsing is
// enabled. This is because clientParamParsing is only relevant when
// clientSegmentCache is enabled.
if (
result.experimental.clientParamParsing &&
!result.experimental.clientSegmentCache
) {
throw new Error(
`\`experimental.clientParamParsing\` can not be \`true\` when \`experimental.clientSegmentCache\` is \`false\`. Client param parsing is only relevant when client segment cache is enabled.`
)
}
return result as NextConfigComplete return result as NextConfigComplete
} }
...@@ -1329,7 +1349,7 @@ export default async function loadConfig( ...@@ -1329,7 +1349,7 @@ export default async function loadConfig(
checkDeprecations(customConfig as NextConfig, configFileName, silent, dir) checkDeprecations(customConfig as NextConfig, configFileName, silent, dir)
const config = await applyModifyConfig( const config = await applyModifyConfig(
assignDefaults( assignDefaultsAndValidate(
dir, dir,
{ {
configOrigin: 'server', configOrigin: 'server',
...@@ -1534,7 +1554,7 @@ export default async function loadConfig( ...@@ -1534,7 +1554,7 @@ export default async function loadConfig(
phase, phase,
}) })
const completeConfig = assignDefaults( const completeConfig = assignDefaultsAndValidate(
dir, dir,
{ {
configOrigin: relative(dir, path), configOrigin: relative(dir, path),
...@@ -1592,7 +1612,7 @@ export default async function loadConfig( ...@@ -1592,7 +1612,7 @@ export default async function loadConfig(
// always call assignDefaults to ensure settings like // always call assignDefaults to ensure settings like
// reactRoot can be updated correctly even with no next.config.js // reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults( const completeConfig = assignDefaultsAndValidate(
dir, dir,
{ ...clonedDefaultConfig, configFileName }, { ...clonedDefaultConfig, configFileName },
silent silent
......
...@@ -901,8 +901,7 @@ export default class DevServer extends Server { ...@@ -901,8 +901,7 @@ export default class DevServer extends Server {
if ( if (
res.value?.fallbackMode !== undefined && res.value?.fallbackMode !== undefined &&
// This matches the hasGenerateStaticParams logic // This matches the hasGenerateStaticParams logic we do during build.
// we do during build
(!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0)) (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))
) { ) {
// we write the static paths to partial manifest for // we write the static paths to partial manifest for
...@@ -916,6 +915,7 @@ export default class DevServer extends Server { ...@@ -916,6 +915,7 @@ export default class DevServer extends Server {
for (const staticPath of value.staticPaths || []) { for (const staticPath of value.staticPaths || []) {
existingManifest.routes[staticPath] = {} as any existingManifest.routes[staticPath] = {} as any
} }
existingManifest.dynamicRoutes[pathname] = { existingManifest.dynamicRoutes[pathname] = {
dataRoute: null, dataRoute: null,
dataRouteRegex: null, dataRouteRegex: null,
...@@ -925,6 +925,7 @@ export default class DevServer extends Server { ...@@ -925,6 +925,7 @@ export default class DevServer extends Server {
fallbackHeaders: undefined, fallbackHeaders: undefined,
fallbackStatus: undefined, fallbackStatus: undefined,
fallbackRootParams: undefined, fallbackRootParams: undefined,
fallbackRouteParams: undefined,
fallbackSourceRoute: pathname, fallbackSourceRoute: pathname,
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
prefetchDataRouteRegex: undefined, prefetchDataRouteRegex: undefined,
......
...@@ -19,6 +19,8 @@ import { collectRootParamKeys } from '../../build/segment-config/app/collect-roo ...@@ -19,6 +19,8 @@ import { collectRootParamKeys } from '../../build/segment-config/app/collect-roo
import { buildAppStaticPaths } from '../../build/static-paths/app' import { buildAppStaticPaths } from '../../build/static-paths/app'
import { buildPagesStaticPaths } from '../../build/static-paths/pages' import { buildPagesStaticPaths } from '../../build/static-paths/pages'
import { createIncrementalCache } from '../../export/helpers/create-incremental-cache' import { createIncrementalCache } from '../../export/helpers/create-incremental-cache'
import type { AppPageRouteModule } from '../route-modules/app-page/module'
import type { AppRouteRouteModule } from '../route-modules/app-route/module'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
...@@ -108,7 +110,11 @@ export async function loadStaticPaths({ ...@@ -108,7 +110,11 @@ export async function loadStaticPaths({
if (isAppPath) { if (isAppPath) {
const routeModule = components.routeModule const routeModule = components.routeModule
const segments = await collectSegments(routeModule) const segments = 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
)
const isRoutePPREnabled = const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && isAppPageRouteModule(routeModule) &&
......
import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants' import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'
import type { FallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import { getCacheHandlerEntries } from '../use-cache/handlers' import { getCacheHandlerEntries } from '../use-cache/handlers'
import { createLazyResult, type LazyResult } from './lazy-result' import { createLazyResult, type LazyResult } from './lazy-result'
...@@ -77,11 +77,9 @@ export async function getImplicitTags( ...@@ -77,11 +77,9 @@ export async function getImplicitTags(
pathname: string pathname: string
search?: string search?: string
}, },
fallbackRouteParams: null | FallbackRouteParams fallbackRouteParams: null | OpaqueFallbackRouteParams
): Promise<ImplicitTags> { ): Promise<ImplicitTags> {
const tags: string[] = [] const tags: string[] = []
const hasFallbackRouteParams =
fallbackRouteParams && fallbackRouteParams.size > 0
// Add the derived tags from the page. // Add the derived tags from the page.
const derivedTags = getDerivedTags(page) const derivedTags = getDerivedTags(page)
...@@ -92,7 +90,10 @@ export async function getImplicitTags( ...@@ -92,7 +90,10 @@ export async function getImplicitTags(
// Add the tags from the pathname. If the route has unknown params, we don't // Add the tags from the pathname. If the route has unknown params, we don't
// want to add the pathname as a tag, as it will be invalid. // want to add the pathname as a tag, as it will be invalid.
if (url.pathname && !hasFallbackRouteParams) { if (
url.pathname &&
(!fallbackRouteParams || fallbackRouteParams.size === 0)
) {
const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${url.pathname}` const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${url.pathname}`
tags.push(tag) tags.push(tag)
} }
......
...@@ -40,6 +40,7 @@ describe('SharedCacheControls', () => { ...@@ -40,6 +40,7 @@ describe('SharedCacheControls', () => {
fallback: true, fallback: true,
fallbackRootParams: undefined, fallbackRootParams: undefined,
fallbackSourceRoute: undefined, fallbackSourceRoute: undefined,
fallbackRouteParams: undefined,
dataRoute: null, dataRoute: null,
dataRouteRegex: null, dataRouteRegex: null,
prefetchDataRoute: null, prefetchDataRoute: null,
......
...@@ -8,6 +8,7 @@ import type { RouteMatch } from './route-matches/route-match' ...@@ -8,6 +8,7 @@ import type { RouteMatch } from './route-matches/route-match'
import type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers' import type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import type { ServerComponentsHmrCache } from './response-cache' import type { ServerComponentsHmrCache } from './response-cache'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup' import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import type { OpaqueFallbackRouteParams } from './request/fallback-params'
// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules // FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules
export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta') export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
...@@ -235,7 +236,7 @@ export interface RequestMeta { ...@@ -235,7 +236,7 @@ export interface RequestMeta {
/** /**
* DEV only: The fallback params that should be used when validating prerenders during dev * DEV only: The fallback params that should be used when validating prerenders during dev
*/ */
devValidatingFallbackParams?: Map<string, string> devValidatingFallbackParams?: OpaqueFallbackRouteParams
} }
/** /**
......
import { createOpaqueFallbackRouteParams } from './fallback-params'
import type { FallbackRouteParam } from '../../build/static-paths/types'
describe('createOpaqueFallbackRouteParams', () => {
describe('opaque object interface', () => {
const fallbackParams: readonly FallbackRouteParam[] = [
{ paramName: 'slug', paramType: 'dynamic', isParallelRouteParam: false },
{ paramName: 'modal', paramType: 'dynamic', isParallelRouteParam: true },
]
it('has method works correctly', () => {
const result = createOpaqueFallbackRouteParams(fallbackParams)!
expect(result.has('slug')).toBe(true)
expect(result.has('modal')).toBe(true)
expect(result.has('nonexistent')).toBe(false)
expect(result.has('')).toBe(false)
})
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('nonexistent')).toBeUndefined()
expect(result.get('')).toBeUndefined()
})
it('iterator yields correct entries', () => {
const result = createOpaqueFallbackRouteParams(fallbackParams)!
const entries = Array.from(result.entries())
expect(entries).toHaveLength(2)
const [name, [value]] = entries[0]
expect(name).toBe('slug')
expect(value).toMatch(/^%%drp:slug:[a-f0-9]+%%$/)
})
})
})
import { collectFallbackRouteParams } from '../../build/segment-config/app/app-segments'
import type { FallbackRouteParam } from '../../build/static-paths/types'
import type { DynamicParamTypesShort } from '../../shared/lib/app-router-types'
import { InvariantError } from '../../shared/lib/invariant-error'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type'
export type FallbackRouteParams = ReadonlyMap<string, string> import type AppPageRouteModule from '../route-modules/app-page/module'
function getParamKeys(page: string) { function getParamKeys(page: string) {
const pattern = getRouteRegex(page) const pattern = getRouteRegex(page)
...@@ -11,29 +15,159 @@ function getParamKeys(page: string) { ...@@ -11,29 +15,159 @@ function getParamKeys(page: string) {
return Object.keys(matcher(page)) return Object.keys(matcher(page))
} }
export function getFallbackRouteParams( export type OpaqueFallbackRouteParamValue = [
pageOrKeys: string | readonly string[] /**
): FallbackRouteParams | null { * The search value of the fallback route param. This is the opaque key
let keys: readonly string[] * that will be used to replace the dynamic param in the postponed state.
if (typeof pageOrKeys === 'string') { */
keys = getParamKeys(pageOrKeys) searchValue: string,
} else {
keys = pageOrKeys /**
} * 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
>
// If there are no keys, we can return early. /**
if (keys.length === 0) return null * 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
*/
export type OpaqueFallbackRouteParamEntries =
ReturnType<OpaqueFallbackRouteParams['entries']> extends MapIterator<
[infer K, infer V]
>
? ReadonlyArray<[K, V]>
: never
const params = new Map<string, string>() /**
* Creates an opaque fallback route params object from the fallback route params.
*
* @param fallbackRouteParams the fallback route params
* @returns the opaque fallback route params
*/
export function createOpaqueFallbackRouteParams(
fallbackRouteParams: readonly FallbackRouteParam[]
): OpaqueFallbackRouteParams | null {
// If there are no fallback route params, we can return early.
if (fallbackRouteParams.length === 0) return null
// As we're creating unique keys for each of the dynamic route params, we only // As we're creating unique keys for each of the dynamic route params, we only
// need to generate a unique ID once per request because each of the keys will // need to generate a unique ID once per request because each of the keys will
// be also be unique. // be also be unique.
const uniqueID = Math.random().toString(16).slice(2) const uniqueID = Math.random().toString(16).slice(2)
for (const key of keys) { const keys = new Map<string, OpaqueFallbackRouteParamValue>()
params.set(key, `%%drp:${key}:${uniqueID}%%`)
// 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],
])
}
return keys
}
/**
* Gets the fallback route params for a given page. This is an expensive
* operation because it requires parsing the loader tree to extract the fallback
* route params.
*
* @param page the page
* @param routeModule the route module
* @returns the opaque fallback route params
*/
export function getFallbackRouteParams(
page: string,
routeModule: AppPageRouteModule
) {
// First, get the fallback route params based on the provided page.
const unknownParamKeys = new Set(getParamKeys(page))
// Needed when processing fallback route params for catchall routes in
// parallel segments, derive from pathname. This is similar to
// getDynamicParam's pagePath parsing logic.
const pathSegments = page.split('/').filter(Boolean)
const collected = collectFallbackRouteParams(routeModule)
// Then, we have to get the fallback route params from the segments that are
// associated with parallel route segments.
const fallbackRouteParams: FallbackRouteParam[] = []
for (const fallbackRouteParam of collected) {
if (fallbackRouteParam.isParallelRouteParam) {
// Try to see if we can resolve this parameter from the page that was
// passed in.
if (unknownParamKeys.has(fallbackRouteParam.paramName)) {
// The parameter is known, we can skip adding it to the fallback route
// params.
continue
}
if (
fallbackRouteParam.paramType === 'optional-catchall' ||
fallbackRouteParam.paramType === 'catchall'
) {
// If there are any fallback route segments then we can't use the
// pathname to derive the value because it's not complete. We can
// make this assumption because the routes are always resolved left
// to right and the catchall is always the last segment, so any
// route parameters that are unknown will always contribute to the
// pathname and therefore the catchall param too.
if (
collected.some(
(param) =>
!param.isParallelRouteParam &&
unknownParamKeys.has(param.paramName)
)
) {
fallbackRouteParams.push(fallbackRouteParam)
continue
}
if (
pathSegments.length === 0 &&
fallbackRouteParam.paramType !== 'optional-catchall'
) {
// We shouldn't be able to match a catchall segment without any path
// segments if it's not an optional catchall.
throw new InvariantError(
`Unexpected empty path segments match for a pathname "${page}" with param "${fallbackRouteParam.paramName}" of type "${fallbackRouteParam.paramType}"`
)
}
// The path segments are not empty, and the segments didn't contain any
// unknown params, so we know that this particular fallback route param
// route param is not actually unknown, and is known. We can skip adding
// it to the fallback route params.
} else {
// This is some other type of route param that shouldn't get resolved
// statically.
throw new InvariantError(
`Unexpected match for a pathname "${page}" with a param "${fallbackRouteParam.paramName}" of type "${fallbackRouteParam.paramType}"`
)
}
} else if (unknownParamKeys.has(fallbackRouteParam.paramName)) {
// As this is a non-parallel route segment, and it exists in the unknown
// param keys, we know it's a fallback route param.
fallbackRouteParams.push(fallbackRouteParam)
}
} }
return params return createOpaqueFallbackRouteParams(fallbackRouteParams)
} }
...@@ -2,7 +2,7 @@ import { ...@@ -2,7 +2,7 @@ import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import type { FallbackRouteParams } from './fallback-params' import type { OpaqueFallbackRouteParams } from './fallback-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
...@@ -336,7 +336,7 @@ function createRenderParamsInProd(underlyingParams: Params): Promise<Params> { ...@@ -336,7 +336,7 @@ function createRenderParamsInProd(underlyingParams: Params): Promise<Params> {
function createRenderParamsInDev( function createRenderParamsInDev(
underlyingParams: Params, underlyingParams: Params,
devFallbackParams: FallbackRouteParams | null | undefined, devFallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
let hasFallbackParams = false let hasFallbackParams = false
...@@ -419,7 +419,7 @@ function makeHangingParams( ...@@ -419,7 +419,7 @@ function makeHangingParams(
function makeErroringExoticParams( function makeErroringExoticParams(
underlyingParams: Params, underlyingParams: Params,
fallbackParams: FallbackRouteParams, fallbackParams: OpaqueFallbackRouteParams,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy
): Promise<Params> { ): Promise<Params> {
......
...@@ -14,7 +14,7 @@ import { ...@@ -14,7 +14,7 @@ import {
type StaticPrerenderStore, type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { FallbackRouteParams } from './fallback-params' import type { OpaqueFallbackRouteParams } from './fallback-params'
import type { Params, ParamValue } from './params' import type { Params, ParamValue } from './params'
import { import {
describeStringPropertyAccess, describeStringPropertyAccess,
...@@ -136,7 +136,7 @@ function createPrerenderRootParams( ...@@ -136,7 +136,7 @@ function createPrerenderRootParams(
function makeErroringRootParams( function makeErroringRootParams(
underlyingParams: Params, underlyingParams: Params,
fallbackParams: FallbackRouteParams, fallbackParams: OpaqueFallbackRouteParams,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy
): Promise<Params> { ): Promise<Params> {
......
...@@ -34,6 +34,7 @@ function createMockDynamicRoute( ...@@ -34,6 +34,7 @@ function createMockDynamicRoute(
fallbackExpire: undefined, fallbackExpire: undefined,
fallbackHeaders: undefined, fallbackHeaders: undefined,
fallbackStatus: undefined, fallbackStatus: undefined,
fallbackRouteParams: undefined,
fallbackRootParams: undefined, fallbackRootParams: undefined,
fallbackSourceRoute: undefined, fallbackSourceRoute: undefined,
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
......
...@@ -17,7 +17,7 @@ import { ...@@ -17,7 +17,7 @@ import {
import * as vendoredContexts from './vendored/contexts/entrypoints' import * as vendoredContexts from './vendored/contexts/entrypoints'
import type { BaseNextRequest, BaseNextResponse } from '../../base-http' import type { BaseNextRequest, BaseNextResponse } from '../../base-http'
import type { ServerComponentsHmrCache } from '../../response-cache' import type { ServerComponentsHmrCache } from '../../response-cache'
import type { FallbackRouteParams } from '../../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../../request/fallback-params'
import { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher' import { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import { import {
...@@ -56,7 +56,7 @@ type AppPageUserlandModule = { ...@@ -56,7 +56,7 @@ type AppPageUserlandModule = {
export interface AppPageRouteHandlerContext extends RouteModuleHandleContext { export interface AppPageRouteHandlerContext extends RouteModuleHandleContext {
page: string page: string
query: NextParsedUrlQuery query: NextParsedUrlQuery
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
renderOpts: RenderOpts renderOpts: RenderOpts
serverComponentsHmrCache?: ServerComponentsHmrCache serverComponentsHmrCache?: ServerComponentsHmrCache
sharedContext: AppSharedContext sharedContext: AppSharedContext
......
...@@ -125,16 +125,16 @@ export type Segment = ...@@ -125,16 +125,16 @@ export type Segment =
| string | string
| [ | [
// Param name // Param name
string, paramName: string,
// Param cache key (almost the same as the value, but arrays are // Param cache key (almost the same as the value, but arrays are
// concatenated into strings) // concatenated into strings)
// TODO: We should change this to just be the value. Currently we convert // TODO: We should change this to just be the value. Currently we convert
// it back to a value when passing to useParams. It only needs to be // it back to a value when passing to useParams. It only needs to be
// a string when converted to a a cache key, but that doesn't mean we // a string when converted to a a cache key, but that doesn't mean we
// need to store it as that representation. // need to store it as that representation.
string, paramCacheKey: string,
// Dynamic param type // Dynamic param type
DynamicParamTypesShort, dynamicParamType: DynamicParamTypesShort,
] ]
/** /**
......
import type { DynamicParam } from '../../../../server/app-render/app-render' import type { DynamicParam } from '../../../../server/app-render/app-render'
import type { OpaqueFallbackRouteParams } from '../../../../server/request/fallback-params'
import type { Params } from '../../../../server/request/params'
import type { DynamicParamTypesShort } from '../../app-router-types' import type { DynamicParamTypesShort } from '../../app-router-types'
import type { FallbackRouteParams } from '../../../../server/request/fallback-params' import { InvariantError } from '../../invariant-error'
/**
* Gets the value of a param from the params object. This correctly handles the
* case where the param is a fallback route param and encodes the resulting
* value.
*
* @param params - The params object.
* @param segmentKey - The key of the segment.
* @param fallbackRouteParams - The fallback route params.
* @returns The value of the param.
*/
function getParamValue(
params: Params,
segmentKey: string,
fallbackRouteParams: OpaqueFallbackRouteParams | null
) {
let value = params[segmentKey]
if (fallbackRouteParams && 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
} else if (Array.isArray(value)) {
value = value.map((i) => encodeURIComponent(i))
} else if (typeof value === 'string') {
value = encodeURIComponent(value)
}
return value
}
/** /**
* *
...@@ -14,21 +47,17 @@ import type { FallbackRouteParams } from '../../../../server/request/fallback-pa ...@@ -14,21 +47,17 @@ import type { FallbackRouteParams } from '../../../../server/request/fallback-pa
* and optional is, alas, unfortunate. * and optional is, alas, unfortunate.
*/ */
export function getDynamicParam( export function getDynamicParam(
params: { [key: string]: any }, params: Params,
segmentKey: string, segmentKey: string,
dynamicParamType: DynamicParamTypesShort, dynamicParamType: DynamicParamTypesShort,
pagePath: string, pagePath: string,
fallbackRouteParams: FallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
): DynamicParam { ): DynamicParam {
let value = params[segmentKey] let value: string | string[] | undefined = getParamValue(
params,
if (fallbackRouteParams && fallbackRouteParams.has(segmentKey)) { segmentKey,
value = fallbackRouteParams.get(segmentKey) fallbackRouteParams
} else if (Array.isArray(value)) { )
value = value.map((i) => encodeURIComponent(i))
} else if (typeof value === 'string') {
value = encodeURIComponent(value)
}
if (!value) { if (!value) {
const isCatchall = dynamicParamType === 'c' const isCatchall = dynamicParamType === 'c'
...@@ -48,6 +77,7 @@ export function getDynamicParam( ...@@ -48,6 +77,7 @@ export function getDynamicParam(
// handle the case where a catchall or optional catchall does not have a value, // handle the case where a catchall or optional catchall does not have a value,
// e.g. `/foo/bar/hello` and `@slot/[...catchall]` or `@slot/[[...catchall]]` is matched // e.g. `/foo/bar/hello` and `@slot/[...catchall]` or `@slot/[[...catchall]]` is matched
// FIXME: (NAR-335) this should handle prefixed segments
value = pagePath value = pagePath
.split('/') .split('/')
// remove the first empty string // remove the first empty string
...@@ -55,11 +85,20 @@ export function getDynamicParam( ...@@ -55,11 +85,20 @@ export function getDynamicParam(
// replace any dynamic params with the actual values // replace any dynamic params with the actual values
.flatMap((pathSegment) => { .flatMap((pathSegment) => {
const param = parseParameter(pathSegment) const param = parseParameter(pathSegment)
// if the segment matches a param, return the param value // if the segment matches a param, return the param value
// otherwise, it's a static segment, so just return that // otherwise, it's a static segment, so just return that
return params[param.key] ?? param.key return (
getParamValue(params, param.key, fallbackRouteParams) ?? param.key
)
}) })
if (!value) {
throw new InvariantError(
`No value found for segment key: "${segmentKey}"`
)
}
return { return {
param: segmentKey, param: segmentKey,
value, value,
...@@ -67,13 +106,17 @@ export function getDynamicParam( ...@@ -67,13 +106,17 @@ export function getDynamicParam(
// This value always has to be a string. // This value always has to be a string.
treeSegment: [segmentKey, value.join('/'), dynamicParamType], treeSegment: [segmentKey, value.join('/'), dynamicParamType],
} }
} else {
throw new InvariantError(
`Unexpected dynamic param type: ${dynamicParamType}`
)
} }
} }
return { return {
param: segmentKey, param: segmentKey,
// The value that is passed to user code. // The value that is passed to user code.
value: value, value,
// The value that is rendered in the router tree. // The value that is rendered in the router tree.
treeSegment: [ treeSegment: [
segmentKey, segmentKey,
......
...@@ -222,7 +222,6 @@ ...@@ -222,7 +222,6 @@
"test/e2e/app-dir/parallel-routes-and-interception-from-root/parallel-routes-and-interception-from-root.test.ts", "test/e2e/app-dir/parallel-routes-and-interception-from-root/parallel-routes-and-interception-from-root.test.ts",
"test/e2e/app-dir/parallel-routes-and-interception-nested-dynamic-routes/parallel-routes-and-interception-nested-dynamic-routes.test.ts", "test/e2e/app-dir/parallel-routes-and-interception-nested-dynamic-routes/parallel-routes-and-interception-nested-dynamic-routes.test.ts",
"test/e2e/app-dir/parallel-routes-and-interception/parallel-routes-and-interception.test.ts", "test/e2e/app-dir/parallel-routes-and-interception/parallel-routes-and-interception.test.ts",
"test/e2e/app-dir/parallel-routes-breadcrumbs/parallel-routes-breadcrumbs.test.ts",
"test/e2e/app-dir/parallel-routes-catchall-specificity/parallel-routes-catchall-specificity.test.ts", "test/e2e/app-dir/parallel-routes-catchall-specificity/parallel-routes-catchall-specificity.test.ts",
"test/e2e/app-dir/parallel-routes-generate-static-params/parallel-routes-generate-static-params.test.ts", "test/e2e/app-dir/parallel-routes-generate-static-params/parallel-routes-generate-static-params.test.ts",
"test/e2e/app-dir/parallel-routes-revalidation/parallel-routes-revalidation.test.ts", "test/e2e/app-dir/parallel-routes-revalidation/parallel-routes-revalidation.test.ts",
......
import React from 'react' import React, { Suspense } from 'react'
export default function Root({ export default function Root({
children, children,
...@@ -10,8 +10,12 @@ export default function Root({ ...@@ -10,8 +10,12 @@ export default function Root({
return ( return (
<html> <html>
<body> <body>
<div id="slot">{slot}</div> <Suspense>
<div id="children">{children}</div> <div id="slot">{slot}</div>
</Suspense>
<Suspense>
<div id="children">{children}</div>
</Suspense>
</body> </body>
</html> </html>
) )
......
...@@ -10,7 +10,11 @@ const cases: { ...@@ -10,7 +10,11 @@ const cases: {
pathname: string pathname: string
only?: boolean only?: boolean
debug?: true debug?: true
headers?: Record<string, string> headers?: {
rsc?: '1'
'next-router-prefetch'?: '0' | '1' | '2'
'next-router-segment-prefetch'?: string
}
expected: Record<Target, string | null> expected: Record<Target, string | null>
}[] = [ }[] = [
{ {
...@@ -38,6 +42,11 @@ const cases: { ...@@ -38,6 +42,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-path': null,
...@@ -69,6 +78,11 @@ const cases: { ...@@ -69,6 +78,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-path': null,
...@@ -100,6 +114,11 @@ const cases: { ...@@ -100,6 +114,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
// only: true, // only: true,
expected: { expected: {
...@@ -132,6 +151,11 @@ const cases: { ...@@ -132,6 +151,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': '/hello/bobby', 'x-nextjs-rewritten-path': '/hello/bobby',
...@@ -163,6 +187,11 @@ const cases: { ...@@ -163,6 +187,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-path': null,
...@@ -194,6 +223,11 @@ const cases: { ...@@ -194,6 +223,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-path': null,
...@@ -225,6 +259,11 @@ const cases: { ...@@ -225,6 +259,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': '/hello/samantha', 'x-nextjs-rewritten-path': '/hello/samantha',
...@@ -256,6 +295,11 @@ const cases: { ...@@ -256,6 +295,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': '/other', 'x-nextjs-rewritten-path': '/other',
...@@ -295,6 +339,11 @@ const cases: { ...@@ -295,6 +339,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-path': null,
...@@ -393,6 +442,11 @@ const cases: { ...@@ -393,6 +442,11 @@ const cases: {
headers: { headers: {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
...(process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
? {
'next-router-segment-prefetch': '/_tree',
}
: {}),
}, },
expected: { expected: {
'x-nextjs-rewritten-path': '/other', 'x-nextjs-rewritten-path': '/other',
...@@ -418,9 +472,9 @@ describe('rewrite-headers', () => { ...@@ -418,9 +472,9 @@ describe('rewrite-headers', () => {
// Add cache busting param for RSC requests // Add cache busting param for RSC requests
if (headers.rsc === '1') { if (headers.rsc === '1') {
const cacheBustingParam = computeCacheBustingSearchParam( const cacheBustingParam = computeCacheBustingSearchParam(
headers['next-router-prefetch'] ? '1' : '0', headers['next-router-prefetch'],
headers['next-router-segment-prefetch'],
undefined, undefined,
headers['next-router-state-tree'],
undefined undefined
) )
if (cacheBustingParam) { if (cacheBustingParam) {
......
...@@ -2428,6 +2428,7 @@ const runTests = (isDev = false) => { ...@@ -2428,6 +2428,7 @@ const runTests = (isDev = false) => {
"fallback": [], "fallback": [],
}, },
"rsc": { "rsc": {
"clientParamParsing": false,
"contentTypeHeader": "text/x-component", "contentTypeHeader": "text/x-component",
"didPostponeHeader": "x-nextjs-postponed", "didPostponeHeader": "x-nextjs-postponed",
"header": "rsc", "header": "rsc",
......
...@@ -1471,6 +1471,7 @@ function runTests({ dev }) { ...@@ -1471,6 +1471,7 @@ function runTests({ dev }) {
"fallback": [], "fallback": [],
}, },
"rsc": { "rsc": {
"clientParamParsing": false,
"contentTypeHeader": "text/x-component", "contentTypeHeader": "text/x-component",
"didPostponeHeader": "x-nextjs-postponed", "didPostponeHeader": "x-nextjs-postponed",
"header": "rsc", "header": "rsc",
......
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