Unverified Commit f6bda26e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix fallback route params case in app-page handler (#93109)

## Summary
- backport the fallback route params fix from #91737 onto `next-16-2`
- preserve intermediate shells that suspend only for unresolved fallback
params during staged rendering
- add the missing `resolvedRouteParamKeys` request metadata needed by
this branch
parent 70defda2
...@@ -31,6 +31,8 @@ import { ...@@ -31,6 +31,8 @@ import {
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' with { 'turbopack-transition': 'next-server-utility' } import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' with { 'turbopack-transition': 'next-server-utility' }
import { import {
getFallbackRouteParams, getFallbackRouteParams,
getPlaceholderFallbackRouteParams,
buildDynamicSegmentPlaceholder,
createOpaqueFallbackRouteParams, createOpaqueFallbackRouteParams,
type OpaqueFallbackRouteParams, type OpaqueFallbackRouteParams,
} from '../../server/request/fallback-params' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/request/fallback-params' with { 'turbopack-transition': 'next-server-utility' }
...@@ -116,10 +118,7 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code ...@@ -116,10 +118,7 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code
import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' } import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' }
import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' } import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' }
import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' } import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' }
import { import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' }
getParamProperties,
getSegmentParam,
} from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' }
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' }
...@@ -141,22 +140,6 @@ export const routeModule = new AppPageRouteModule({ ...@@ -141,22 +140,6 @@ export const routeModule = new AppPageRouteModule({
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
}) })
function buildDynamicSegmentPlaceholder(
param: Pick<FallbackRouteParam, 'paramName' | 'paramType'>
): string {
const { repeat, optional } = getParamProperties(param.paramType)
if (optional) {
return `[[...${param.paramName}]]`
}
if (repeat) {
return `[...${param.paramName}]`
}
return `[${param.paramName}]`
}
/** /**
* Builds the cache key for the most complete prerenderable shell we can derive * Builds the cache key for the most complete prerenderable shell we can derive
* from the shell that matched this request. Only params that can still be * from the shell that matched this request. Only params that can still be
...@@ -1343,17 +1326,65 @@ export async function handler( ...@@ -1343,17 +1326,65 @@ export async function handler(
} }
} }
const placeholderFallbackRouteParams =
// When a request carries dynamic placeholder values (e.g. "[slug]"),
// defer only the unresolved subset instead of forcing all fallback
// params to suspend.
!routeModule.isDev &&
pageIsDynamic &&
prerenderInfo?.fallbackRouteParams
? getPlaceholderFallbackRouteParams(
params as
| Record<string, undefined | string | string[]>
| undefined,
prerenderInfo.fallbackRouteParams
)
: null
const fallbackRouteParamsForRender =
placeholderFallbackRouteParams &&
placeholderFallbackRouteParams.length > 0
? placeholderFallbackRouteParams
: prerenderInfo?.fallbackRouteParams
const hasPlaceholderFallbackRouteParams =
placeholderFallbackRouteParams != null &&
placeholderFallbackRouteParams.length > 0
// When route-module.ts resolved partial nxtP* params during
// background revalidation, filter fallbackRouteParams to only the
// params that are still unresolved. This lets doRender produce an
// intermediate PPR shell that suspends only for those params.
let effectiveFallbackRouteParams: FallbackRouteParam[] | null = null
if (nextConfig.cacheComponents && prerenderInfo?.fallbackRouteParams) {
const resolvedKeys = getRequestMeta(req, 'resolvedRouteParamKeys')
if (resolvedKeys && resolvedKeys.size > 0) {
effectiveFallbackRouteParams =
prerenderInfo.fallbackRouteParams.filter(
(param) => !resolvedKeys.has(param.paramName)
)
}
}
const fallbackRouteParams = const fallbackRouteParams =
// In production or when debugging the static shell for a // In production or when debugging the static shell for a
// non-prerendered URL, use the prerender manifest's fallback route // non-prerendered URL, use the prerender manifest's fallback route
// params which correctly identifies which params are unknown. // params which correctly identifies which params are unknown.
((isProduction && getRequestMeta(req, 'renderFallbackShell')) || ((isProduction && getRequestMeta(req, 'renderFallbackShell')) ||
hasPlaceholderFallbackRouteParams ||
(isDebugStaticShell && !isPrerendered)) && (isDebugStaticShell && !isPrerendered)) &&
prerenderInfo?.fallbackRouteParams fallbackRouteParamsForRender
? createOpaqueFallbackRouteParams(prerenderInfo.fallbackRouteParams) ? createOpaqueFallbackRouteParams(fallbackRouteParamsForRender)
: isDebugFallbackShell : // For intermediate shells where some params are resolved and
? getFallbackRouteParams(normalizedSrcPage, routeModule) // others still have placeholders, use the filtered subset so the
: null // prerender suspends only for the unresolved params.
effectiveFallbackRouteParams &&
effectiveFallbackRouteParams.length > 0 &&
effectiveFallbackRouteParams.length <
(prerenderInfo?.fallbackRouteParams?.length ?? 0)
? createOpaqueFallbackRouteParams(effectiveFallbackRouteParams)
: isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
// For staged dynamic rendering (Cached Navigations) and debug static // For staged dynamic rendering (Cached Navigations) and debug static
// shell rendering, pass the fallback params via request meta so the // shell rendering, pass the fallback params via request meta so the
...@@ -1367,7 +1398,7 @@ export async function handler( ...@@ -1367,7 +1398,7 @@ export async function handler(
prerenderInfo?.fallbackRouteParams prerenderInfo?.fallbackRouteParams
) { ) {
const fallbackParams = createOpaqueFallbackRouteParams( const fallbackParams = createOpaqueFallbackRouteParams(
prerenderInfo.fallbackRouteParams fallbackRouteParamsForRender ?? prerenderInfo.fallbackRouteParams
) )
if (fallbackParams) { if (fallbackParams) {
......
...@@ -299,6 +299,13 @@ export interface RequestMeta { ...@@ -299,6 +299,13 @@ export interface RequestMeta {
*/ */
minimalMode?: boolean minimalMode?: boolean
/**
* When background revalidation resolves some route params but not others,
* tracks the param keys that are no longer placeholders so only the
* unresolved subset suspends in intermediate PPR shells.
*/
resolvedRouteParamKeys?: Set<string>
/** /**
* The fallback params for this route. In dev, used for validating prerenders. * The fallback params for this route. In dev, used for validating prerenders.
* In production, used to defer params resolution during staged rendering. * In production, used to defer params resolution during staged rendering.
......
import { import {
buildDynamicSegmentPlaceholder,
createOpaqueFallbackRouteParams, createOpaqueFallbackRouteParams,
getFallbackRouteParams, getFallbackRouteParams,
getPlaceholderFallbackRouteParams,
} from './fallback-params' } from './fallback-params'
import type { FallbackRouteParam } from '../../build/static-paths/types' import type { FallbackRouteParam } from '../../build/static-paths/types'
import type AppPageRouteModule from '../route-modules/app-page/module' import type AppPageRouteModule from '../route-modules/app-page/module'
...@@ -72,6 +74,54 @@ describe('createOpaqueFallbackRouteParams', () => { ...@@ -72,6 +74,54 @@ describe('createOpaqueFallbackRouteParams', () => {
}) })
}) })
describe('placeholder fallback route params', () => {
it('builds route placeholders by dynamic param type', () => {
expect(
buildDynamicSegmentPlaceholder({
paramName: 'slug',
paramType: 'dynamic',
})
).toBe('[slug]')
expect(
buildDynamicSegmentPlaceholder({
paramName: 'slug',
paramType: 'catchall',
})
).toBe('[...slug]')
expect(
buildDynamicSegmentPlaceholder({
paramName: 'slug',
paramType: 'optional-catchall',
})
).toBe('[[...slug]]')
})
it('returns only fallback params that are still placeholders', () => {
const fallbackParams: readonly FallbackRouteParam[] = [
{ paramName: 'team', paramType: 'dynamic' },
{ paramName: 'project', paramType: 'dynamic' },
{ paramName: 'slug', paramType: 'catchall' },
{ paramName: 'optional', paramType: 'optional-catchall' },
]
const result = getPlaceholderFallbackRouteParams(
{
team: '[team]',
project: 'dashboard',
slug: ['[...slug]'],
optional: '[[...optional]]',
},
fallbackParams
)
expect(result).toEqual([
{ paramName: 'team', paramType: 'dynamic' },
{ paramName: 'slug', paramType: 'catchall' },
{ paramName: 'optional', paramType: 'optional-catchall' },
])
})
})
describe('getFallbackRouteParams', () => { describe('getFallbackRouteParams', () => {
describe('Regular Routes (children segments)', () => { describe('Regular Routes (children segments)', () => {
it('should extract single dynamic segment from children route', () => { it('should extract single dynamic segment from children route', () => {
...@@ -190,6 +240,24 @@ describe('getFallbackRouteParams', () => { ...@@ -190,6 +240,24 @@ describe('getFallbackRouteParams', () => {
expect(result!.has('projectSlug')).toBe(true) expect(result!.has('projectSlug')).toBe(true)
expect(result!.has('teamSlug')).toBe(false) expect(result!.has('teamSlug')).toBe(false)
}) })
it('should treat encoded placeholders as dynamic segments', () => {
// Tree: /[teamSlug]/[projectSlug] but page is /vercel/%5BprojectSlug%5D
const loaderTree = createLoaderTree(
'',
{},
createLoaderTree('[teamSlug]', {}, createLoaderTree('[projectSlug]'))
)
const routeModule = createMockRouteModule(loaderTree)
const result = getFallbackRouteParams(
'/vercel/%5BprojectSlug%5D',
routeModule
)
expect(result).not.toBeNull()
expect(result!.has('projectSlug')).toBe(true)
expect(result!.has('teamSlug')).toBe(false)
})
}) })
describe('Route Groups', () => { describe('Route Groups', () => {
......
...@@ -5,6 +5,7 @@ import { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type' ...@@ -5,6 +5,7 @@ import { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type'
import type AppPageRouteModule from '../route-modules/app-page/module' import type AppPageRouteModule from '../route-modules/app-page/module'
import { parseAppRoute } from '../../shared/lib/router/routes/app' import { parseAppRoute } from '../../shared/lib/router/routes/app'
import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree' import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'
import { getParamProperties } from '../../shared/lib/router/utils/get-segment-param'
export type OpaqueFallbackRouteParamValue = [ export type OpaqueFallbackRouteParamValue = [
/** /**
...@@ -74,6 +75,37 @@ export function createOpaqueFallbackRouteParams( ...@@ -74,6 +75,37 @@ export function createOpaqueFallbackRouteParams(
return keys return keys
} }
export function buildDynamicSegmentPlaceholder(
param: Pick<FallbackRouteParam, 'paramName' | 'paramType'>
): string {
const { repeat, optional } = getParamProperties(param.paramType)
if (optional) {
return `[[...${param.paramName}]]`
}
if (repeat) {
return `[...${param.paramName}]`
}
return `[${param.paramName}]`
}
export function getPlaceholderFallbackRouteParams(
params: Record<string, undefined | string | string[]> | undefined,
fallbackRouteParams: readonly FallbackRouteParam[]
): FallbackRouteParam[] {
return fallbackRouteParams.filter((param) => {
const placeholder = buildDynamicSegmentPlaceholder(param)
const value = params?.[param.paramName]
return (
value === placeholder ||
(Array.isArray(value) && value.length === 1 && value[0] === placeholder)
)
})
}
/** /**
* Gets the fallback route params for a given page. This is an expensive * 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 * operation because it requires parsing the loader tree to extract the fallback
......
...@@ -71,3 +71,134 @@ describe('getParamsFromRouteMatches', () => { ...@@ -71,3 +71,134 @@ describe('getParamsFromRouteMatches', () => {
expect(params).toEqual({ slug: 'hello-world', rest: ['im-the', 'rest'] }) expect(params).toEqual({ slug: 'hello-world', rest: ['im-the', 'rest'] })
}) })
}) })
describe('normalizeDynamicRouteParams', () => {
it('should reject encoded default placeholders for dynamic params', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: '%5BteamSlug%5D',
project: '%5Bproject%5D',
},
true
)
expect(result).toEqual({
params: {},
hasValidParams: false,
})
})
it('should reject doubly encoded default placeholders for dynamic params', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: '%255BteamSlug%255D',
project: '%255Bproject%255D',
},
true
)
expect(result).toEqual({
params: {},
hasValidParams: false,
})
})
it('should continue accepting regular dynamic values', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'vercel',
project: 'nextjs',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'vercel',
project: 'nextjs',
},
hasValidParams: true,
})
})
it('should not decode matched params beyond the route matcher decode', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'acme',
project: '%23hash',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'acme',
project: '%23hash',
},
hasValidParams: true,
})
})
it('should not reject non-placeholder values that only contain decoded placeholder text', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'acme',
project: '%5Bproject%5D-suffix',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'acme',
project: '%5Bproject%5D-suffix',
},
hasValidParams: true,
})
})
})
...@@ -112,6 +112,34 @@ export function normalizeDynamicRouteParams( ...@@ -112,6 +112,34 @@ export function normalizeDynamicRouteParams(
defaultRouteMatches: ParsedUrlQuery, defaultRouteMatches: ParsedUrlQuery,
ignoreMissingOptional: boolean ignoreMissingOptional: boolean
) { ) {
const isDefaultValueMatch = (
candidateValue: string | undefined,
defaultValue: string
) => {
if (!candidateValue) {
return false
}
let normalizedCandidateValue = normalizeRscURL(candidateValue)
for (let i = 0; i < 3; i++) {
if (normalizedCandidateValue === defaultValue) {
return true
}
const decodedCandidateValue = decodeQueryPathParameter(
normalizedCandidateValue
)
if (decodedCandidateValue === normalizedCandidateValue) {
break
}
normalizedCandidateValue = decodedCandidateValue
}
return false
}
let hasValidParams = true let hasValidParams = true
let params: ParsedUrlQuery = {} let params: ParsedUrlQuery = {}
...@@ -133,10 +161,12 @@ export function normalizeDynamicRouteParams( ...@@ -133,10 +161,12 @@ export function normalizeDynamicRouteParams(
const isDefaultValue = Array.isArray(defaultValue) const isDefaultValue = Array.isArray(defaultValue)
? defaultValue.some((defaultVal) => { ? defaultValue.some((defaultVal) => {
return Array.isArray(value) return Array.isArray(value)
? value.some((val) => val.includes(defaultVal)) ? value.some((val) => isDefaultValueMatch(val, defaultVal))
: value?.includes(defaultVal) : isDefaultValueMatch(value, defaultVal)
}) })
: value?.includes(defaultValue as string) : Array.isArray(value)
? value.some((val) => isDefaultValueMatch(val, defaultValue as string))
: isDefaultValueMatch(value, defaultValue as string)
if ( if (
isDefaultValue || isDefaultValue ||
......
...@@ -60,6 +60,19 @@ export type NormalizedAppRouteSegment = ...@@ -60,6 +60,19 @@ export type NormalizedAppRouteSegment =
| StaticAppRouteSegment | StaticAppRouteSegment
| DynamicAppRouteSegment | DynamicAppRouteSegment
function normalizeEncodedDynamicPlaceholder(segment: string): string {
if (!/%5b|%5d/i.test(segment)) {
return segment
}
try {
const decodedSegment = decodeURIComponent(segment)
return getSegmentParam(decodedSegment) ? decodedSegment : segment
} catch {
return segment
}
}
export function parseAppRouteSegment(segment: string): AppRouteSegment | null { export function parseAppRouteSegment(segment: string): AppRouteSegment | null {
if (segment === '') { if (segment === '') {
return null return null
...@@ -180,8 +193,10 @@ export function parseAppRoute( ...@@ -180,8 +193,10 @@ export function parseAppRoute(
let interceptedRoute: AppRoute | NormalizedAppRoute | undefined let interceptedRoute: AppRoute | NormalizedAppRoute | undefined
for (const segment of pathnameSegments) { for (const segment of pathnameSegments) {
const normalizedSegment = normalizeEncodedDynamicPlaceholder(segment)
// Parse the segment into an AppSegment. // Parse the segment into an AppSegment.
const appSegment = parseAppRouteSegment(segment) const appSegment = parseAppRouteSegment(normalizedSegment)
if (!appSegment) { if (!appSegment) {
continue continue
} }
......
export default function ProjectDomainsSettingsLoading() {
return (
<div data-team-project-settings-domains-loading="true">
Loading project domains settings...
</div>
)
}
import { cacheLife } from 'next/cache'
import Link from 'next/link'
import { Suspense } from 'react'
import { LinkAccordion } from '../../../../../../components/link-accordion'
type Params = { teamSlug: string; project: string }
export default function ProjectDomainsSettingsPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="team-project-settings-domains-page">
<Suspense
fallback={
<div data-loading="true">
Loading project settings domains page...
</div>
}
>
<ProjectDomainsSettingsContent params={params} />
</Suspense>
<nav data-nav-link-list="true">
<ul>
<li>
<Link
href="/acme/dashboard/settings"
data-nav-link="/acme/dashboard/settings"
>
Navigate: acme/dashboard/settings
</Link>
</li>
<li>
<Link
href="/globex/portal/settings"
data-nav-link="/globex/portal/settings"
>
Navigate: globex/portal/settings
</Link>
</li>
<li>
<Link
href="/acme/dashboard/settings/domains"
data-nav-link="/acme/dashboard/settings/domains"
>
Navigate: acme/dashboard/settings/domains
</Link>
</li>
<li>
<Link
href="/globex/portal/settings/domains"
data-nav-link="/globex/portal/settings/domains"
>
Navigate: globex/portal/settings/domains
</Link>
</li>
</ul>
</nav>
<div data-related-link-list="true">
<LinkAccordion href="/acme/dashboard/settings/domains">
Related route: acme/dashboard/settings/domains
</LinkAccordion>
<LinkAccordion href="/globex/portal/settings/domains">
Related route: globex/portal/settings/domains
</LinkAccordion>
</div>
</div>
)
}
async function ProjectDomainsSettingsContent({
params,
}: {
params: Promise<Params>
}) {
'use cache'
cacheLife({ stale: 0, revalidate: 1, expire: 60 })
const { teamSlug, project } = await params
const marker = Date.now()
return (
<div data-team-project-settings-domains-content="true">
{`Project domains settings content - team: ${teamSlug}, project: ${project}, marker: ${marker}`}
</div>
)
}
import { ReactNode } from 'react'
export default function ProjectSettingsLayout({
children,
}: {
children: ReactNode
}) {
return (
<div data-project-settings-layout="domains-variant">
<h2>Project Settings Layout (domains variant)</h2>
{children}
</div>
)
}
export default function TeamProjectLoading() {
return (
<div data-team-project-loading="true">Loading team project page...</div>
)
}
import { cacheLife } from 'next/cache'
import Link from 'next/link'
import { Suspense } from 'react'
import { LinkAccordion } from '../../../components/link-accordion'
type Params = { teamSlug: string; project: string }
export default function TeamProjectPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="team-project-page">
<Suspense
fallback={<div data-loading="true">Loading team/project route...</div>}
>
<TeamProjectContent params={params} />
</Suspense>
<nav data-nav-link-list="true">
<ul>
<li>
<Link href="/" data-nav-link="/">
Navigate: home
</Link>
</li>
<li>
<Link href="/acme/dashboard" data-nav-link="/acme/dashboard">
Navigate: acme/dashboard
</Link>
</li>
<li>
<Link href="/globex/portal" data-nav-link="/globex/portal">
Navigate: globex/portal
</Link>
</li>
<li>
<Link
href="/acme/dashboard/settings"
data-nav-link="/acme/dashboard/settings"
>
Navigate: acme/dashboard/settings
</Link>
</li>
<li>
<Link
href="/globex/portal/settings"
data-nav-link="/globex/portal/settings"
>
Navigate: globex/portal/settings
</Link>
</li>
<li>
<Link
href="/acme/dashboard/settings/domains"
data-nav-link="/acme/dashboard/settings/domains"
>
Navigate: acme/dashboard/settings/domains
</Link>
</li>
<li>
<Link
href="/globex/portal/settings/domains"
data-nav-link="/globex/portal/settings/domains"
>
Navigate: globex/portal/settings/domains
</Link>
</li>
</ul>
</nav>
<div data-related-link-list="true">
<LinkAccordion href="/acme/dashboard">
Related route: acme/dashboard
</LinkAccordion>
<LinkAccordion href="/globex/portal">
Related route: globex/portal
</LinkAccordion>
<LinkAccordion href="/acme/dashboard/settings/domains">
Related route: acme/dashboard/settings/domains
</LinkAccordion>
<LinkAccordion href="/globex/portal/settings/domains">
Related route: globex/portal/settings/domains
</LinkAccordion>
</div>
</div>
)
}
async function TeamProjectContent({ params }: { params: Promise<Params> }) {
'use cache'
cacheLife({ stale: 0, revalidate: 1, expire: 60 })
const { teamSlug, project } = await params
const marker = Date.now()
return (
<div data-team-project-content="true">
{`Team project content - team: ${teamSlug}, project: ${project}, marker: ${marker}`}
</div>
)
}
import { ReactNode } from 'react'
export default function ProjectSettingsLayout({
children,
}: {
children: ReactNode
}) {
return (
<div data-project-settings-layout="default">
<h2>Project Settings Layout</h2>
{children}
</div>
)
}
import { cacheLife } from 'next/cache'
import Link from 'next/link'
import { Suspense } from 'react'
import { LinkAccordion } from '../../../../components/link-accordion'
type Params = { teamSlug: string; project: string }
export default function ProjectSettingsPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="team-project-settings-page">
<Suspense
fallback={<div data-loading="true">Loading settings page...</div>}
>
<ProjectSettingsContent params={params} />
</Suspense>
<nav data-nav-link-list="true">
<ul>
<li>
<Link href="/" data-nav-link="/">
Navigate: home
</Link>
</li>
<li>
<Link
href="/acme/dashboard/settings/domains"
data-nav-link="/acme/dashboard/settings/domains"
>
Navigate: acme/dashboard/settings/domains
</Link>
</li>
<li>
<Link
href="/globex/portal/settings/domains"
data-nav-link="/globex/portal/settings/domains"
>
Navigate: globex/portal/settings/domains
</Link>
</li>
</ul>
</nav>
<div data-related-link-list="true">
<LinkAccordion href="/acme/dashboard/settings/domains">
Related route: acme/dashboard/settings/domains
</LinkAccordion>
<LinkAccordion href="/globex/portal/settings/domains">
Related route: globex/portal/settings/domains
</LinkAccordion>
</div>
</div>
)
}
async function ProjectSettingsContent({ params }: { params: Promise<Params> }) {
'use cache'
cacheLife({ stale: 0, revalidate: 1, expire: 60 })
const { teamSlug, project } = await params
const marker = Date.now()
return (
<div data-team-project-settings-content="true">
{`Project settings overview content - team: ${teamSlug}, project: ${project}, marker: ${marker}`}
</div>
)
}
import { revalidatePath, revalidateTag } from 'next/cache'
import { NextRequest } from 'next/server'
type RevalidateMode =
| 'tag-layout-expireNow'
| 'tag-layout-max'
| 'tag-layout-legacy'
| 'path-root-layout'
| 'path-team-layout'
| 'path-team-page'
function isRevalidateMode(value: string): value is RevalidateMode {
return (
value === 'tag-layout-expireNow' ||
value === 'tag-layout-max' ||
value === 'tag-layout-legacy' ||
value === 'path-root-layout' ||
value === 'path-team-layout' ||
value === 'path-team-page'
)
}
export async function GET(request: NextRequest) {
const modeQuery = request.nextUrl.searchParams.get('mode')
const mode: RevalidateMode =
modeQuery && isRevalidateMode(modeQuery)
? modeQuery
: 'tag-layout-expireNow'
switch (mode) {
case 'tag-layout-expireNow':
revalidateTag('_N_T_/layout', 'expireNow')
break
case 'tag-layout-max':
revalidateTag('_N_T_/layout', 'max')
break
case 'tag-layout-legacy':
// Intentionally test the deprecated call shape without a profile arg.
// @ts-expect-error
revalidateTag('_N_T_/layout')
break
case 'path-root-layout':
revalidatePath('/', 'layout')
break
case 'path-team-layout':
revalidatePath('/acme/dashboard', 'layout')
break
case 'path-team-page':
revalidatePath('/acme/dashboard')
break
default:
break
}
return Response.json({
revalidated: true,
mode,
})
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
import { RevalidateControls } from '../components/revalidate-controls'
export default function HomePage() {
return (
<div id="home-page">
<h1>Root Dynamic Route Vary Params</h1>
<p>
Prefetch dynamic team/project routes and validate segment payload
params.
</p>
<ul data-nav-link-list="true">
<li>
<Link href="/acme/dashboard" data-nav-link="/acme/dashboard">
Navigate: acme/dashboard
</Link>
</li>
<li>
<Link href="/globex/portal" data-nav-link="/globex/portal">
Navigate: globex/portal
</Link>
</li>
<li>
<Link
href="/acme/dashboard/settings/domains"
data-nav-link="/acme/dashboard/settings/domains"
>
Navigate: acme/dashboard/settings/domains
</Link>
</li>
<li>
<Link
href="/globex/portal/settings/domains"
data-nav-link="/globex/portal/settings/domains"
>
Navigate: globex/portal/settings/domains
</Link>
</li>
</ul>
<ul>
<li>
<LinkAccordion href="/acme/dashboard">
Team project: acme/dashboard
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/globex/portal">
Team project: globex/portal
</LinkAccordion>
</li>
</ul>
<RevalidateControls />
</div>
)
}
'use server'
import { revalidateTag } from 'next/cache'
export async function revalidateLayoutByTagExpireNowAction() {
revalidateTag('_N_T_/layout', 'expireNow')
return {
mode: 'server-action-tag-layout-expireNow',
revalidated: true,
}
}
export async function revalidateLayoutByTagMaxAction() {
revalidateTag('_N_T_/layout', 'max')
return {
mode: 'server-action-tag-layout-max',
revalidated: true,
}
}
export async function revalidateLayoutByTagLegacyAction() {
// Intentionally test the deprecated call shape without a profile arg.
// @ts-expect-error
revalidateTag('_N_T_/layout')
return {
mode: 'server-action-tag-layout-legacy',
revalidated: true,
}
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children?: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const displayChildren = children !== undefined ? children : href
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{displayChildren}
</Link>
) : (
<>{displayChildren} (link is hidden)</>
)}
</>
)
}
'use client'
import { useState } from 'react'
import {
revalidateLayoutByTagExpireNowAction,
revalidateLayoutByTagLegacyAction,
revalidateLayoutByTagMaxAction,
} from '../app/revalidate-actions'
type ApiRevalidateMode =
| 'tag-layout-expireNow'
| 'tag-layout-max'
| 'tag-layout-legacy'
| 'path-root-layout'
| 'path-team-layout'
| 'path-team-page'
type ServerActionMode =
| 'server-action-tag-layout-expireNow'
| 'server-action-tag-layout-max'
| 'server-action-tag-layout-legacy'
export function RevalidateControls() {
const [result, setResult] = useState('idle')
const [isPending, setIsPending] = useState(false)
const runApiRevalidate = async (mode: ApiRevalidateMode) => {
setIsPending(true)
try {
const response = await fetch(`/api/revalidate-layout?mode=${mode}`, {
method: 'GET',
})
const data = await response.json()
setResult(JSON.stringify(data))
} catch (error) {
setResult(
JSON.stringify({
error: error instanceof Error ? error.message : 'unknown error',
mode,
})
)
} finally {
setIsPending(false)
}
}
const runServerActionRevalidate = async (mode: ServerActionMode) => {
setIsPending(true)
try {
const data =
mode === 'server-action-tag-layout-expireNow'
? await revalidateLayoutByTagExpireNowAction()
: mode === 'server-action-tag-layout-max'
? await revalidateLayoutByTagMaxAction()
: await revalidateLayoutByTagLegacyAction()
setResult(JSON.stringify(data))
} catch (error) {
setResult(
JSON.stringify({
error: error instanceof Error ? error.message : 'unknown error',
mode,
})
)
} finally {
setIsPending(false)
}
}
return (
<div data-revalidate-controls="true">
<button
id="revalidate-in-browser-tag-layout-expireNow"
type="button"
disabled={isPending}
onClick={() => runApiRevalidate('tag-layout-expireNow')}
>
Browser Revalidate Tag Layout (expireNow)
</button>
<button
id="revalidate-in-browser-tag-layout-max"
type="button"
disabled={isPending}
onClick={() => runApiRevalidate('tag-layout-max')}
>
Browser Revalidate Tag Layout (max)
</button>
<button
id="revalidate-in-browser-tag-layout-legacy"
type="button"
disabled={isPending}
onClick={() => runApiRevalidate('tag-layout-legacy')}
>
Browser Revalidate Tag Layout (legacy)
</button>
<button
id="revalidate-in-browser-server-action-tag-layout-expireNow"
type="button"
disabled={isPending}
onClick={() =>
runServerActionRevalidate('server-action-tag-layout-expireNow')
}
>
Server Action Revalidate Tag Layout (expireNow)
</button>
<button
id="revalidate-in-browser-server-action-tag-layout-max"
type="button"
disabled={isPending}
onClick={() =>
runServerActionRevalidate('server-action-tag-layout-max')
}
>
Server Action Revalidate Tag Layout (max)
</button>
<button
id="revalidate-in-browser-server-action-tag-layout-legacy"
type="button"
disabled={isPending}
onClick={() =>
runServerActionRevalidate('server-action-tag-layout-legacy')
}
>
Server Action Revalidate Tag Layout (legacy)
</button>
<div id="revalidate-result" data-revalidate-result={result}>
{result}
</div>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
cacheLife: {
expireNow: {
stale: 0,
revalidate: 0,
expire: 0,
},
},
experimental: {
optimisticRouting: true,
varyParams: true,
},
}
module.exports = nextConfig
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<{ revalidated: boolean }>
) {
const pathParam = req.query['path']
if (!pathParam) {
return res.status(400).json({ revalidated: false })
}
const paths = Array.isArray(pathParam) ? pathParam : [pathParam]
try {
await Promise.all(paths.map((path) => res.revalidate(path)))
return res.status(200).json({ revalidated: true })
} catch (error) {
console.error('Failed to revalidate paths:', paths, error)
return res.status(500).json({ revalidated: false })
}
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('segment cache - root params segment prefetch', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('prefetching is disabled in dev mode', () => {})
return
}
it('does not encode root param placeholders in segment-prefetch responses', async () => {
let act: ReturnType<typeof createRouterAct>
const segmentPrefetchBodies: Array<Promise<string>> = []
const browser = await next.browser('/root-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
p.on('response', (response) => {
const request = response.request()
if (request.headers()['next-router-segment-prefetch']) {
segmentPrefetchBodies.push(response.text().catch(() => ''))
}
})
},
})
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/aaa"]'
)
await toggle.click()
},
{ includes: 'Root param page content - param: aaa' }
)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/bbb"]'
)
await toggle.click()
},
{ includes: 'Root param page content - param: bbb' }
)
const settledSegmentPrefetchBodies = await Promise.all(
segmentPrefetchBodies
)
expect(settledSegmentPrefetchBodies.length).toBeGreaterThan(0)
expect(
settledSegmentPrefetchBodies.some((body) =>
body.includes('%5BrootParam%5D')
)
).toBe(false)
})
})
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/rewrites/:path*',
destination: `http://127.0.0.1:${process.env.TEST_INTERMEDIARY_PORT}/rewrites/:path*`,
},
]
},
}
module.exports = nextConfig
export default function Page() {
return <p>hello world</p>
}
import net from 'net'
import http from 'http'
import { createNext, NextInstance } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
describe('rewrite-request-smuggling', () => {
if ((global as any).isNextDeploy) {
it('should skip deploy', () => {})
return
}
let backend: http.Server
let backendPort: number
let intermediary: http.Server
let intermediaryPort: number
let next: NextInstance
const backendRequests: string[] = []
async function sendSmugglingPayload({
nextPort,
connectionHeader,
method = 'DELETE',
rewritePath = '/rewrites/poc',
}: {
nextPort: number
connectionHeader: string
method?: 'DELETE' | 'OPTIONS'
rewritePath?: string
}) {
const smuggledRequest = Buffer.from(
`GET /secret HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\n\r\n`,
'latin1'
)
const chunkSize = Buffer.from(
`${smuggledRequest.length.toString(16).toUpperCase()}\r\n`,
'latin1'
)
const payload = Buffer.concat([
Buffer.from(
`${method} ${rewritePath} HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\nTransfer-Encoding: chunked\r\nConnection: ${connectionHeader}\r\n\r\n`,
'latin1'
),
chunkSize,
smuggledRequest,
Buffer.from('\r\n0\r\n\r\n', 'latin1'),
])
await new Promise<void>((resolve, reject) => {
const socket = net.createConnection({
host: '127.0.0.1',
port: nextPort,
})
socket.once('connect', () => {
socket.write(payload)
})
socket.once('error', reject)
socket.setTimeout(1000, () => socket.destroy())
socket.once('close', () => resolve())
})
}
beforeAll(async () => {
backendPort = await findPort()
intermediaryPort = await findPort()
backend = http.createServer((req, res) => {
backendRequests.push(`${req.method} ${req.url}`)
if (req.url?.startsWith('/rewrites/')) {
res.statusCode = 200
res.end('rewrite-ok')
return
}
if (req.url === '/secret') {
res.statusCode = 200
res.end('secret')
return
}
res.statusCode = 404
res.end('not-found')
})
intermediary = http.createServer((req, res) => {
const connectionHeader = Array.isArray(req.headers['connection'])
? req.headers['connection'].join(',')
: req.headers['connection'] || ''
const hopByHopHeaders = connectionHeader
.split(',')
.map((h) => h.trim().toLowerCase())
.filter(Boolean)
const stripTransferEncodingUnconditionally =
req.url?.startsWith('/rewrites/non-rfc-strip') || false
const forwardHeaders: Record<string, string | string[]> = {}
for (const [key, value] of Object.entries(req.headers)) {
if (key === 'connection') continue
if (stripTransferEncodingUnconditionally && key === 'transfer-encoding')
continue
if (hopByHopHeaders.includes(key)) continue
if (value !== undefined) {
forwardHeaders[key] = value
}
}
forwardHeaders.connection = stripTransferEncodingUnconditionally
? connectionHeader.toLowerCase().includes('close')
? 'close'
: 'keep-alive'
: 'keep-alive'
const proxyReq = http.request(
{
hostname: '127.0.0.1',
port: backendPort,
method: req.method,
path: req.url,
headers: forwardHeaders,
},
(proxyRes) => {
res.writeHead(proxyRes.statusCode || 500, proxyRes.headers)
proxyRes.pipe(res)
}
)
proxyReq.on('error', () => {
res.statusCode = 502
res.end('Bad Gateway')
})
req.pipe(proxyReq)
})
await new Promise<void>((resolve, reject) => {
backend.listen(backendPort, '127.0.0.1', resolve)
backend.once('error', reject)
})
await new Promise<void>((resolve, reject) => {
intermediary.listen(intermediaryPort, '127.0.0.1', resolve)
intermediary.once('error', reject)
})
next = await createNext({
files: __dirname,
env: {
TEST_INTERMEDIARY_PORT: String(intermediaryPort),
},
})
})
afterAll(async () => {
await next?.destroy()
await new Promise<void>((resolve) => intermediary.close(() => resolve()))
await new Promise<void>((resolve) => backend.close(() => resolve()))
})
it('does not smuggle a second request when using keep-alive only', async () => {
backendRequests.length = 0
const nextPort = Number(new URL(next.url).port)
await sendSmugglingPayload({ nextPort, connectionHeader: 'keep-alive' })
await retry(async () => {
expect(backendRequests).toContain('DELETE /rewrites/poc')
})
expect(backendRequests).not.toContain('GET /secret')
})
it('does not smuggle a second request with keep-alive, upgrade', async () => {
backendRequests.length = 0
const nextPort = Number(new URL(next.url).port)
await sendSmugglingPayload({
nextPort,
connectionHeader: 'keep-alive, upgrade',
})
await retry(async () => {
expect(backendRequests).toContain('DELETE /rewrites/poc')
})
expect(backendRequests).not.toContain('GET /secret')
})
it('does not smuggle a second request with Transfer-Encoding, upgrade', async () => {
backendRequests.length = 0
const nextPort = Number(new URL(next.url).port)
await sendSmugglingPayload({
nextPort,
connectionHeader: 'Transfer-Encoding, upgrade',
})
await retry(async () => {
expect(backendRequests).toContain('DELETE /rewrites/poc')
})
expect(backendRequests).not.toContain('GET /secret')
})
it('does not smuggle a second request for OPTIONS with Transfer-Encoding, upgrade', async () => {
backendRequests.length = 0
const nextPort = Number(new URL(next.url).port)
await sendSmugglingPayload({
nextPort,
method: 'OPTIONS',
connectionHeader: 'Transfer-Encoding, upgrade',
})
await retry(async () => {
expect(backendRequests).toContain('OPTIONS /rewrites/poc')
})
expect(backendRequests).not.toContain('GET /secret')
})
it('does not smuggle a second request when an intermediary strips transfer-encoding unconditionally', async () => {
backendRequests.length = 0
const nextPort = Number(new URL(next.url).port)
await sendSmugglingPayload({
nextPort,
method: 'OPTIONS',
rewritePath: '/rewrites/non-rfc-strip',
connectionHeader: 'keep-alive, upgrade',
})
await retry(async () => {
expect(backendRequests).toContain('OPTIONS /rewrites/non-rfc-strip')
})
expect(backendRequests).not.toContain('GET /secret')
})
})
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