Unverified Commit bfcf687f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix unexpected query parameters in adapter deployments (#98584)

The Vercel adapter enables `passQuery: true`, which forwards named route
captures to prerender functions as query parameters instead of using the
legacy route-matches header. When a request bypasses prerendered output,
this also exposes internal path-building captures through application
`searchParams`. With `experimental.collapseAdapterRoutes` disabled, RSC
renders can receive `rscSuffix=.rsc`. With the flag enabled, document
and Server Action renders can also receive `rscSuffix=`, and collapsed
fallback shells can expose values such as `shellPrefix=en`. These
additions can overwrite user query parameters and cause unnecessary
navigation retries.

We fix this in `handleBuildComplete`, where Next.js generates these
path-only helper captures. Unnamed captures and numbered destination
references preserve the rewrite behavior without requiring adapters to
recognize and filter Next.js's internal helper capture names.

When using an adapter, we now emit unnamed captures for these path-only
values. For example, `(?<shellPrefix>de|en)` and its destination
reference `$shellPrefix` become `(de|en)` and `$1` when no locale
capture precedes the group. Likewise, `(?<rscSuffix>...)` and
`$rscSuffix` become `(...)` and a positional reference such as `$2` when
one capture precedes the suffix. The generator accounts for parameter
and locale captures and escapes literal base paths. Destination
substitution runs once, preserving captured text and correctly
distinguishing references such as `$1` and `$10`.

Cache-bypass rules, route counts, and route ordering remain unchanged.
User-supplied `rscSuffix` and `shellPrefix` remain valid query
parameters. Standard `next dev` and `next start` routing, and Vercel's
legacy deployment path, do not use these generated adapter routes, and
thus are not affected.

Verified by running the [full deploy test
matrix](https://github.com/vercel/next.js/actions/runs/34835432358)
against this PR.
parent 6866b944
...@@ -7,30 +7,54 @@ export function replaceDestination( ...@@ -7,30 +7,54 @@ export function replaceDestination(
regexMatches: RegExpMatchArray | null, regexMatches: RegExpMatchArray | null,
hasCaptures: Record<string, string> hasCaptures: Record<string, string>
): string { ): string {
let result = destination const captureKeys = Object.keys(hasCaptures)
// Replace numbered captures from regex ($1, $2, etc.)
if (regexMatches) { if (regexMatches) {
// Replace numbered groups (skip index 0 which is the full match) for (let index = 1; index < regexMatches.length; index++) {
for (let i = 1; i < regexMatches.length; i++) { captureKeys.push(String(index))
const value = regexMatches[i] ?? ''
result = result.replace(new RegExp(`\\$${i}`, 'g'), value)
} }
// Replace named groups ($name)
if (regexMatches.groups) { if (regexMatches.groups) {
for (const [name, value] of Object.entries(regexMatches.groups)) { captureKeys.push(...Object.keys(regexMatches.groups))
result = result.replace(new RegExp(`\\$${name}`, 'g'), value ?? '')
}
} }
} }
// Replace named captures from has conditions if (captureKeys.length === 0) {
for (const [name, value] of Object.entries(hasCaptures)) { return destination
result = result.replace(new RegExp(`\\$${name}`, 'g'), value)
} }
return result const capturePattern = captureKeys
.sort((first, second) => second.length - first.length)
.map((key) => {
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
return /^\d+$/.test(key) ? `${escapedKey}(?!\\d)` : escapedKey
})
.join('|')
// Replace placeholders once. Captured paths can contain literal text such as
// $2 or $d$segment that must not become another substitution.
return destination.replace(
new RegExp(`\\$(${capturePattern})`, 'g'),
(placeholder, key: string) => {
if (regexMatches) {
const index = Number(key)
if (
Number.isInteger(index) &&
index > 0 &&
index < regexMatches.length &&
String(index) === key
) {
return regexMatches[index] ?? ''
}
if (regexMatches.groups && Object.hasOwn(regexMatches.groups, key)) {
return regexMatches.groups[key] ?? ''
}
}
if (Object.hasOwn(hasCaptures, key)) {
return hasCaptures[key]
}
return placeholder
}
)
} }
/** /**
......
...@@ -2110,6 +2110,10 @@ export async function handleBuildComplete({ ...@@ -2110,6 +2110,10 @@ export async function handleBuildComplete({
(page) => prerenderManifest.dynamicRoutes[page]?.fallback === false (page) => prerenderManifest.dynamicRoutes[page]?.fallback === false
) )
: undefined : undefined
const escapedBasePath =
config.basePath && config.basePath !== '/'
? escapeStringRegexp(path.posix.join('/', config.basePath))
: ''
for (const route of routesManifest.dynamicRoutes) { for (const route of routesManifest.dynamicRoutes) {
// An earlier entry in this loop serves this shell. // An earlier entry in this loop serves this shell.
...@@ -2133,6 +2137,10 @@ export async function handleBuildComplete({ ...@@ -2133,6 +2137,10 @@ export async function handleBuildComplete({
// An entry for a whole run of shells matches every prefix in that run. // An entry for a whole run of shells matches every prefix in that run.
// The destination copies the prefix that matched. // The destination copies the prefix that matched.
// //
// The prefix and RSC suffix use unnamed captures. Adapters can forward
// named captures to the application query when they bypass prerendered
// output.
//
// This replacement runs on the pattern for the page, and `sourceRegex` // This replacement runs on the pattern for the page, and `sourceRegex`
// below prefixes the result with the base path and the locale group. That // below prefixes the result with the base path and the locale group. That
// order is deliberate. The search text anchors at `^`, and here that // order is deliberate. The search text anchors at `^`, and here that
...@@ -2143,18 +2151,24 @@ export async function handleBuildComplete({ ...@@ -2143,18 +2151,24 @@ export async function handleBuildComplete({
const pagePattern = fallbackShellRun const pagePattern = fallbackShellRun
? routeRegex.namedRegex.replace( ? routeRegex.namedRegex.replace(
`^/${escapeStringRegexp(fallbackShellRun.prefixes[0])}/`, `^/${escapeStringRegexp(fallbackShellRun.prefixes[0])}/`,
`^/(?<shellPrefix>${fallbackShellRun.prefixes () =>
.map((prefix) => escapeStringRegexp(prefix)) `^/(${fallbackShellRun.prefixes
.join('|')})/` .map((prefix) => escapeStringRegexp(prefix))
.join('|')})/`
) )
: routeRegex.namedRegex : routeRegex.namedRegex
const pagePath = fallbackShellRun const pagePath = fallbackShellRun
? path.posix.join('/', '$shellPrefix', fallbackShellRun.tail) ? path.posix.join(
'/',
shouldLocalize ? '$2' : '$1',
fallbackShellRun.tail
)
: route.page : route.page
const sourceRegex = pagePattern.replace( const sourceRegex = pagePattern.replace(
'^', '^',
`^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}` () =>
`^${escapedBasePath}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}`
) )
const destination = const destination =
path.posix.join( path.posix.join(
...@@ -2163,6 +2177,13 @@ export async function handleBuildComplete({ ...@@ -2163,6 +2177,13 @@ export async function handleBuildComplete({
shouldLocalize ? '/$nextLocale' : '', shouldLocalize ? '/$nextLocale' : '',
pagePath pagePath
) + getDestinationQuery(route.routeKeys) ) + getDestinationQuery(route.routeKeys)
// Count capture names, not parameter names. An interception route can
// capture the same parameter with both nxtP and nxtI names.
const suffixCaptureIndex =
Object.keys(routeRegex.routeKeys).length +
(shouldLocalize ? 1 : 0) +
(fallbackShellRun ? 1 : 0) +
1
const hasAppPages = Boolean(appPageKeys && appPageKeys.length > 0) const hasAppPages = Boolean(appPageKeys && appPageKeys.length > 0)
...@@ -2196,15 +2217,18 @@ export async function handleBuildComplete({ ...@@ -2196,15 +2217,18 @@ export async function handleBuildComplete({
// An optional group is unsafe here. An adapter, or the router that // An optional group is unsafe here. An adapter, or the router that
// consumes its output, can resolve the placeholders in a destination // consumes its output, can resolve the placeholders in a destination
// from the match result rather than from the pattern. A group that does // from the match result rather than from the pattern. A group that does
// not match is then absent from that result, and the literal text // not match is then absent from that result, and the destination
// `$rscSuffix` stays in the destination. // placeholder stays unresolved.
dynamicRoutes.push({ dynamicRoutes.push({
source: pagePath, source: pagePath,
sourceRegex: sourceRegex.replace( sourceRegex: sourceRegex.replace(
new RegExp(escapeStringRegexp('(?:/)?$')), new RegExp(escapeStringRegexp('(?:/)?$')),
'(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$' '(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$'
),
destination: destination.replace(
/($|\?)/,
(separator) => `$${suffixCaptureIndex}${separator}`
), ),
destination: destination?.replace(/($|\?)/, '$rscSuffix$1'),
has: plainHas, has: plainHas,
missing: undefined, missing: undefined,
}) })
...@@ -2218,9 +2242,12 @@ export async function handleBuildComplete({ ...@@ -2218,9 +2242,12 @@ export async function handleBuildComplete({
source: pagePath + '.rsc', source: pagePath + '.rsc',
sourceRegex: sourceRegex.replace( sourceRegex: sourceRegex.replace(
new RegExp(escapeStringRegexp('(?:/)?$')), new RegExp(escapeStringRegexp('(?:/)?$')),
'(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$' '(\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$'
),
destination: destination.replace(
/($|\?)/,
(separator) => `$${suffixCaptureIndex}${separator}`
), ),
destination: destination?.replace(/($|\?)/, '$rscSuffix$1'),
has: suffixedHas, has: suffixedHas,
missing: undefined, missing: undefined,
}) })
...@@ -2246,7 +2273,7 @@ export async function handleBuildComplete({ ...@@ -2246,7 +2273,7 @@ export async function handleBuildComplete({
source: route.page, source: route.page,
sourceRegex: segmentRoute.source.replace( sourceRegex: segmentRoute.source.replace(
'^', '^',
`^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?` () => `^${escapedBasePath}[/]?`
), ),
destination: path.posix.join( destination: path.posix.join(
'/', '/',
......
...@@ -157,7 +157,7 @@ function splitShellPage( ...@@ -157,7 +157,7 @@ function splitShellPage(
* with shells for `acme/en`, `acme/de` and `globex/en`, that pattern holds: * with shells for `acme/en`, `acme/de` and `globex/en`, that pattern holds:
* *
* ``` * ```
* (?<shellPrefix>acme/en|acme/de|globex/en) * (acme/en|acme/de|globex/en)
* ``` * ```
* *
* A pattern that offered a choice per param instead, such as * A pattern that offered a choice per param instead, such as
......
import { nextTestSetup } from 'e2e-utils'
describe('adapter-route-i18n', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it.each([
{ prefix: '', locale: 'en' },
{ prefix: '/fr', locale: 'fr' },
])(
'renders the $locale locale with a base path',
async ({ prefix, locale }) => {
const browser = await next.browser(
`/base${prefix}/legacy/one?term=kept`,
{ permissions: [] }
)
expect(await browser.elementById(`${locale}-one`).text()).toBe(
`${locale}:one`
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual({
slug: 'one',
term: 'kept',
})
}
)
it('navigates to an explicit locale without reloading the document', async () => {
const browser = await next.browser('/base/legacy/one', {
permissions: [],
})
await browser.eval('window.__testDocument = "retained"')
await browser.elementById('next-page').click()
expect(await browser.elementById('fr-two').text()).toBe('fr:two')
expect(JSON.parse(await browser.elementById('query').text())).toEqual({
slug: 'two',
term: 'next',
})
expect(new URL(await browser.url()).pathname).toBe('/base/fr/legacy/two')
expect(await browser.eval('window.__testDocument')).toBe('retained')
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
basePath: '/base',
cacheComponents: false,
partialPrefetching: false,
experimental: { cachedNavigations: false },
i18n: { locales: ['en', 'fr'], defaultLocale: 'en', localeDetection: false },
}
export default nextConfig
import Link from 'next/link'
import type { GetServerSideProps, InferGetServerSidePropsType } from 'next'
import type { ParsedUrlQuery } from 'querystring'
export const getServerSideProps: GetServerSideProps<{
slug: string
locale: string
query: ParsedUrlQuery
}> = async ({ params, locale, query }) => {
if (typeof params?.slug !== 'string') {
return { notFound: true }
}
if (locale === undefined) {
throw new Error('Expected a configured locale')
}
return { props: { slug: params.slug, locale, query } }
}
export default function Page({
slug,
locale,
query,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<>
<p id={`${locale}-${slug}`}>{`${locale}:${slug}`}</p>
<pre id="query">{JSON.stringify(query)}</pre>
<Link
id="next-page"
href="/legacy/two?term=next"
locale="fr"
prefetch={false}
>
French page
</Link>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
const basePath = '/base'
const routePath = '/many/one/two/three/four/five/six/seven/eight'
const rootParameters = [
{ team: 'acme', region: 'east' },
{ team: 'cash$2', region: 'east' },
{ team: 'cash$3', region: 'east' },
{ team: 'sparse', region: 'west' },
]
const parameters = {
first: 'one',
second: 'two',
third: 'three',
fourth: 'four',
fifth: 'five',
sixth: 'six',
seventh: 'seven',
eighth: 'eight',
ninth: 'nine',
}
describe.each([false, true])(
'adapter route navigation, collapseAdapterRoutes: %s',
(collapseAdapterRoutes) => {
const { next } = nextTestSetup({
files: __dirname,
env: { TEST_COLLAPSE_ADAPTER_ROUTES: String(collapseAdapterRoutes) },
})
async function startBrowser(pathname: string) {
let act: ReturnType<typeof createRouterAct> | undefined
const browser = await next.browser(`${basePath}${pathname}`, {
permissions: [],
beforePageLoad(page) {
act = createRouterAct(page, { includeAppShellRequests: true })
},
})
if (act === undefined) {
throw new Error('Router act was not initialized')
}
await browser.eval('window.__testDocument = "retained"')
return { browser, act }
}
it.each(rootParameters)(
'renders every parameter on a direct visit within $team/$region',
async ({ team, region }) => {
const { browser } = await startBrowser(
`/${team}/${region}${routePath}/nine?term=kept`
)
expect(
JSON.parse(await browser.elementById('parameters').text())
).toEqual({
team: encodeURIComponent(team),
region: encodeURIComponent(region),
...parameters,
})
expect(JSON.parse(await browser.elementById('query').text())).toEqual({
term: 'kept',
})
}
)
it.each(rootParameters)(
'navigates within $team/$region without prefetching',
async ({ team, region }) => {
const prefix = `/${team}/${region}`
// App Router passes encoded parameter values to components.
const expectedParameters = {
team: encodeURIComponent(team),
region: encodeURIComponent(region),
...parameters,
}
const { browser, act } = await startBrowser(`${prefix}/hub`)
expect(await browser.elementById('root-params').text()).toBe(
`${expectedParameters.team}:${expectedParameters.region}`
)
const href = `/${expectedParameters.team}/${expectedParameters.region}${routePath}/nine?term=kept`
await act(
async () => {
await browser.elementByCss(`a[href="${basePath}${href}"]`).click()
},
{ includes: 'Article nine' }
)
expect(
JSON.parse(await browser.elementById('parameters').text())
).toEqual(expectedParameters)
expect(JSON.parse(await browser.elementById('query').text())).toEqual({
term: 'kept',
})
expect(decodeURIComponent(new URL(await browser.url()).pathname)).toBe(
`${basePath}${prefix}${routePath}/nine`
)
expect(await browser.eval('window.__testDocument')).toBe('retained')
}
)
// @force-gate prefetching
it('prefetches page content before navigation', async () => {
const { browser, act } = await startBrowser('/acme/east/hub')
const href = `/acme/east${routePath}/prefetched?term=kept`
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${href}"]`)
.click()
},
{ includes: 'Many parameters' }
)
await act(
async () => {
await browser.elementByCss(`a[href="${basePath}${href}"]`).click()
},
{ includes: 'Article prefetched' }
)
expect(
JSON.parse(await browser.elementById('parameters').text())
).toEqual({
team: 'acme',
region: 'east',
...parameters,
ninth: 'prefetched',
})
expect(JSON.parse(await browser.elementById('query').text())).toEqual({
term: 'kept',
})
expect(await browser.eval('window.__testDocument')).toBe('retained')
})
it('returns 404 outside the base path', async () => {
for (const invalidBasePath of ['/base-other', '/bas', '/baseX']) {
const response = await next.fetch(`${invalidBasePath}/acme/east/hub`)
expect(response.status).toBe(404)
}
})
}
)
import { Suspense } from 'react'
import Link from 'next/link'
import { LinkAccordion } from '../../../../components/link-accordion'
async function Links({
params,
}: {
params: Promise<{ team: string; region: string }>
}) {
const { team, region } = await params
const prefix = `/${team}/${region}/many/one/two/three/four/five/six/seven/eight`
return (
<>
<Link href={`${prefix}/nine?term=kept`} prefetch={false}>
Navigate without prefetching
</Link>
<LinkAccordion href={`${prefix}/prefetched?term=kept`} />
</>
)
}
export default function Page({
params,
}: {
params: Promise<{ team: string; region: string }>
}) {
return (
<Suspense fallback={<p>Loading links</p>}>
<Links params={params} />
</Suspense>
)
}
import { Suspense, type ReactNode } from 'react'
export function generateStaticParams() {
return [
{ team: 'acme', region: 'east' },
{ team: 'acme', region: 'west' },
{ team: 'sparse', region: 'east' },
{ team: 'cash$2', region: 'east' },
{ team: 'cash$3', region: 'east' },
]
}
async function RootParams({
params,
}: {
params: Promise<{ team: string; region: string }>
}) {
const { team, region } = await params
return <p id="root-params">{`${team}:${region}`}</p>
}
export default function Root({
children,
params,
}: {
children: ReactNode
params: Promise<{ team: string; region: string }>
}) {
return (
<html>
<body>
<Suspense fallback={<p>Loading root parameters</p>}>
<RootParams params={params} />
</Suspense>
{children}
</body>
</html>
)
}
import { Suspense } from 'react'
// This page tests routing, not an instant-navigation guarantee.
export const instant = false
type Props = {
params: Promise<Record<string, string>>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
async function Content({ params, searchParams }: Props) {
const parameters = await params
const query = await searchParams
return (
<>
<p id="article">{`Article ${parameters.ninth}`}</p>
<pre id="parameters">{JSON.stringify(parameters)}</pre>
<pre id="query">{JSON.stringify(query)}</pre>
</>
)
}
export default function Page(props: Props) {
return (
<>
<h1>Many parameters</h1>
<Suspense fallback={<p>Loading article</p>}>
<Content {...props} />
</Suspense>
</>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({ href }: { href: string }) {
const [visible, setVisible] = useState(false)
return (
<>
<input
type="checkbox"
aria-label={`Show ${href}`}
data-link-accordion={href}
checked={visible}
onChange={() => setVisible(!visible)}
/>
{visible ? <Link href={href}>Open article</Link> : null}
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
basePath: '/base',
cacheComponents: true,
partialPrefetching: false,
experimental: {
cachedNavigations: true,
optimisticRouting: true,
prefetchInlining: false,
collapseAdapterRoutes: process.env.TEST_COLLAPSE_ADAPTER_ROUTES === 'true',
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
describe.each([false, true])(
'adapter query parameters, collapseAdapterRoutes: %s',
(collapseAdapterRoutes) => {
const { next } = nextTestSetup({
files: __dirname,
env: {
TEST_COLLAPSE_ADAPTER_ROUTES: String(collapseAdapterRoutes),
},
})
async function startBrowser(url: string) {
let act: ReturnType<typeof createRouterAct> | undefined
const browser = await next.browser(url, {
permissions: [],
beforePageLoad(page) {
act = createRouterAct(page, { includeAppShellRequests: true })
},
})
if (act === undefined) {
throw new Error('Router act was not initialized')
}
return { browser, act }
}
describe.each([
{ name: 'no search parameters', search: '', searchParams: {} },
{
name: 'user search parameters',
search:
'?rscSuffix=first&rscSuffix=second&shellPrefix=user&term=example',
searchParams: {
rscSuffix: ['first', 'second'],
shellPrefix: 'user',
term: 'example',
},
},
])('$name', ({ search, searchParams }) => {
it.each([false, true])(
'preserves search parameters in the document, draft mode: %s',
async (draft) => {
const { browser } = await startBrowser(
`${draft ? '/draft' : '/article/one'}${search}`
)
expect(await browser.elementById('article').text()).toBe(
`${draft ? 'Draft' : 'Published'} article one`
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual(
searchParams
)
}
)
it.each([false, true])(
'preserves search parameters without retrying navigation, draft mode: %s',
async (draft) => {
const { browser, act } = await startBrowser(
draft ? '/draft' : '/article/one'
)
const href = `/article/two${search}`
await act(
async () => {
await browser.elementByCss(`a[href="${href}"]`).click()
},
{ includes: `${draft ? 'Draft' : 'Published'} article two` }
)
expect(await browser.elementById('article').text()).toBe(
`${draft ? 'Draft' : 'Published'} article two`
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual(
searchParams
)
expect(new URL(await browser.url()).pathname).toBe('/article/two')
}
)
it('preserves search parameters after a non-draft Server Action', async () => {
const { browser, act } = await startBrowser(`/article/one${search}`)
await act(async () => {
await browser.elementById('update-cookie').click()
})
expect(await browser.elementById('shared-render').text()).toBe(
'Cookie updated'
)
expect(await browser.elementById('article').text()).toBe(
'Published article one'
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual(
searchParams
)
})
it.each(['en', 'de'])(
'preserves search parameters in a fallback shell document for %s',
async (locale) => {
const { browser } = await startBrowser(
`/${locale}/posts/one${search}`
)
expect(await browser.elementById('article').text()).toBe(
'Published article one'
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual(
searchParams
)
}
)
it('preserves search parameters when navigating through a fallback shell', async () => {
const { browser, act } = await startBrowser('/en/posts/one')
const href = `/en/posts/two${search}`
await act(
async () => {
await browser.elementByCss(`a[href="${href}"]`).click()
},
{ includes: 'Published article two' }
)
expect(await browser.elementById('article').text()).toBe(
'Published article two'
)
expect(JSON.parse(await browser.elementById('query').text())).toEqual(
searchParams
)
expect(new URL(await browser.url()).pathname).toBe('/en/posts/two')
})
})
}
)
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'de' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export { default } from '../../../article/[slug]/page'
'use server'
import { cookies } from 'next/headers'
export async function updateCookie() {
const cookieStore = await cookies()
cookieStore.set('query-test', 'set')
}
import { Suspense } from 'react'
import { draftMode } from 'next/headers'
import { connection } from 'next/server'
type Props = {
params: Promise<{ slug: string }>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
export function generateStaticParams() {
return [{ slug: 'built' }]
}
async function Content({ params, searchParams }: Props) {
await connection()
const { slug } = await params
const query = await searchParams
const { isEnabled } = await draftMode()
return (
<>
<p id="article">{`${isEnabled ? 'Draft' : 'Published'} article ${slug}`}</p>
<p id="query">{JSON.stringify(query)}</p>
</>
)
}
export default function Page(props: Props) {
return (
<Suspense fallback={<p>Loading article</p>}>
<Content {...props} />
</Suspense>
)
}
import { draftMode } from 'next/headers'
import { NextResponse, type NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const draft = await draftMode()
draft.enable()
const destination = new URL('/article/one', request.url)
destination.search = request.nextUrl.search
return NextResponse.redirect(destination)
}
import { Suspense, type ReactNode } from 'react'
import Link from 'next/link'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { updateCookie } from './actions'
async function SharedContent() {
await connection()
const cookieStore = await cookies()
return (
<p id="shared-render">
{cookieStore.has('query-test') ? 'Cookie updated' : 'Cookie absent'}
</p>
)
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense fallback={<p>Loading shared content</p>}>
<SharedContent />
</Suspense>
<nav>
<Link href="/article/two" prefetch={false}>
Article two
</Link>
<Link
href="/article/two?rscSuffix=first&rscSuffix=second&shellPrefix=user&term=example"
prefetch={false}
>
Article two with search parameters
</Link>
<Link href="/en/posts/two" prefetch={false}>
English article two
</Link>
<Link
href="/en/posts/two?rscSuffix=first&rscSuffix=second&shellPrefix=user&term=example"
prefetch={false}
>
English article two with search parameters
</Link>
</nav>
<form action={updateCookie}>
<button id="update-cookie">Update an ordinary cookie</button>
</form>
{children}
</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: false,
// Exercise the prerender bypass with ordinary browser requests, not only
// draft mode.
htmlLimitedBots: /.*/,
experimental: {
cachedNavigations: true,
optimisticRouting: true,
collapseAdapterRoutes: process.env.TEST_COLLAPSE_ADAPTER_ROUTES === 'true',
},
}
export default nextConfig
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
describe('parallel-routes-and-interception-from-root', () => { describe.each([false, true])(
const { next, isNextDeploy } = nextTestSetup({ 'parallel-routes-and-interception-from-root, collapseAdapterRoutes: %s',
files: __dirname, (collapseAdapterRoutes) => {
}) const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
it('should interpolate [locale] in "/[locale]/example/(...)[locale]/intercepted"', async () => { nextConfig: { experimental: { collapseAdapterRoutes } },
const browser = await next.browser('/en/example')
expect(await browser.elementByCss('h1').text()).toBe('Example Page')
expect(await browser.elementByCss('p').text()).toBe('Locale: en')
if (!isNextDeploy) {
expect(next.cliOutput).toInclude('RootLayout rendered, locale: en')
}
// Referenced by commented out assertion below, see TODO message
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const cliOutputLength = next.cliOutput.length
await browser.elementByCss('a').click()
await retry(async () => {
expect(await browser.elementByCss('h2').text()).toBe(
'Page intercepted from root'
)
}) })
// Ensure that the locale is still correctly rendered in the root layout. it('should interpolate [locale] in "/[locale]/example/(...)[locale]/intercepted"', async () => {
expect(await browser.elementByCss('p').text()).toBe('Locale: en') const browser = await next.browser('/en/example')
// ...and that the root layout was not rerendered. expect(await browser.elementByCss('h1').text()).toBe('Example Page')
if (!isNextDeploy) { expect(await browser.elementByCss('p').text()).toBe('Locale: en')
// FIXME: This assertion is temporarily disabled. Clicking the link should
// not re-render the root layout. This is happening because the response if (!isNextDeploy) {
// includes extra search params in the page segment that shouldn't be expect(next.cliOutput).toInclude('RootLayout rendered, locale: en')
// there: "__PAGE__?{\"locale":\"en\"}" instead of "__PAGE__". On the }
// surface, it looks like the route params are accidentally being treated
// as search params. // Referenced by commented out assertion below, see TODO message
// // eslint-disable-next-line @typescript-eslint/no-unused-vars
// This assertion used to pass despite the mismatch, because client was const cliOutputLength = next.cliOutput.length
// more permissive about validating the tree when receiving a dynamic
// response from the server. But now we intentionally compare all the await browser.elementByCss('a').click()
// segments, including the search params.
// await retry(async () => {
// Regardless, we need to fix whatever's causing the params to be treated expect(await browser.elementByCss('h2').text()).toBe(
// as search params. 'Page intercepted from root'
// )
// Correct behavior: })
// expect(next.cliOutput.slice(cliOutputLength)).not.toInclude(
// 'RootLayout rendered, locale: en' // Ensure that the locale is still correctly rendered in the root layout.
// ) expect(await browser.elementByCss('p').text()).toBe('Locale: en')
}
}) // ...and that the root layout was not rerendered.
}) if (!isNextDeploy) {
// FIXME: This assertion is temporarily disabled. Clicking the link should
// not re-render the root layout. This is happening because the response
// includes extra search params in the page segment that shouldn't be
// there: "__PAGE__?{\"locale":\"en\"}" instead of "__PAGE__". On the
// surface, it looks like the route params are accidentally being treated
// as search params.
//
// This assertion used to pass despite the mismatch, because client was
// more permissive about validating the tree when receiving a dynamic
// response from the server. But now we intentionally compare all the
// segments, including the search params.
//
// Regardless, we need to fix whatever's causing the params to be treated
// as search params.
//
// Correct behavior:
// expect(next.cliOutput.slice(cliOutputLength)).not.toInclude(
// 'RootLayout rendered, locale: en'
// )
}
})
}
)
...@@ -44,32 +44,32 @@ describe('adapter dynamic routes (cache components)', () => { ...@@ -44,32 +44,32 @@ describe('adapter dynamic routes (cache components)', () => {
"7 entries "7 entries
/[lang] /[lang]
^[/]?/(?<nxtPlang>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPlang>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[lang]$rscSuffix?nxtPlang=$nxtPlang -> /[lang]$2?nxtPlang=$nxtPlang
/$shellPrefix/fallback-shell/[slug] /$1/fallback-shell/[slug]
^[/]?/(?<shellPrefix>de|en)/fallback\\-shell/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(de|en)/fallback\\-shell/(?<nxtPslug>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /$shellPrefix/fallback-shell/[slug]$rscSuffix?nxtPslug=$nxtPslug -> /$1/fallback-shell/[slug]$3?nxtPslug=$nxtPslug
/[lang]/fallback-shell/[slug] /[lang]/fallback-shell/[slug]
^[/]?/(?<nxtPlang>[^/]+?)/fallback\\-shell/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPlang>[^/]+?)/fallback\\-shell/(?<nxtPslug>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[lang]/fallback-shell/[slug]$rscSuffix?nxtPlang=$nxtPlang&nxtPslug=$nxtPslug -> /[lang]/fallback-shell/[slug]$3?nxtPlang=$nxtPlang&nxtPslug=$nxtPslug
/[lang]/ppr /[lang]/ppr
^[/]?/(?<nxtPlang>[^/]+?)/ppr(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPlang>[^/]+?)/ppr(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[lang]/ppr$rscSuffix?nxtPlang=$nxtPlang -> /[lang]/ppr$2?nxtPlang=$nxtPlang
/[lang]/static /[lang]/static
^[/]?/(?<nxtPlang>[^/]+?)/static(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPlang>[^/]+?)/static(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[lang]/static$rscSuffix?nxtPlang=$nxtPlang -> /[lang]/static$2?nxtPlang=$nxtPlang
/$shellPrefix/[slug] /$1/[slug]
^[/]?/(?<shellPrefix>de|en)/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(de|en)/(?<nxtPslug>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /$shellPrefix/[slug]$rscSuffix?nxtPslug=$nxtPslug -> /$1/[slug]$3?nxtPslug=$nxtPslug
/[lang]/[slug] /[lang]/[slug]
^[/]?/(?<nxtPlang>[^/]+?)/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPlang>[^/]+?)/(?<nxtPslug>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[lang]/[slug]$rscSuffix?nxtPlang=$nxtPlang&nxtPslug=$nxtPslug" -> /[lang]/[slug]$3?nxtPlang=$nxtPlang&nxtPslug=$nxtPslug"
`) `)
}) })
}) })
...@@ -56,24 +56,24 @@ describe('adapter dynamic routes (legacy)', () => { ...@@ -56,24 +56,24 @@ describe('adapter dynamic routes (legacy)', () => {
-> /static-two -> /static-two
/blog/[slug] /blog/[slug]
^[/]?/blog/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/blog/(?<nxtPslug>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /blog/[slug]$rscSuffix?nxtPslug=$nxtPslug -> /blog/[slug]$2?nxtPslug=$nxtPslug
/docs/[lang]/accounts /docs/[lang]/accounts
^[/]?/docs/(?<nxtPlang>[^/]+?)/accounts(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/docs/(?<nxtPlang>[^/]+?)/accounts(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /docs/[lang]/accounts$rscSuffix?nxtPlang=$nxtPlang -> /docs/[lang]/accounts$2?nxtPlang=$nxtPlang
/docs/[lang]/functions /docs/[lang]/functions
^[/]?/docs/(?<nxtPlang>[^/]+?)/functions(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/docs/(?<nxtPlang>[^/]+?)/functions(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /docs/[lang]/functions$rscSuffix?nxtPlang=$nxtPlang -> /docs/[lang]/functions$2?nxtPlang=$nxtPlang
/docs/[lang]/guide /docs/[lang]/guide
^[/]?/docs/(?<nxtPlang>[^/]+?)/guide(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/docs/(?<nxtPlang>[^/]+?)/guide(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /docs/[lang]/guide$rscSuffix?nxtPlang=$nxtPlang -> /docs/[lang]/guide$2?nxtPlang=$nxtPlang
/legacy/[id].rsc /legacy/[id].rsc
^[/]?/legacy/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$ ^[/]?/legacy/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$
-> /legacy/[id]$rscSuffix?nxtPid=$nxtPid -> /legacy/[id]$2?nxtPid=$nxtPid
/legacy/[id] /legacy/[id]
^[/]?/legacy/(?<nxtPid>[^/]+?)(?:/)?$ ^[/]?/legacy/(?<nxtPid>[^/]+?)(?:/)?$
......
...@@ -44,25 +44,25 @@ describe('adapter dynamic routes (no root params)', () => { ...@@ -44,25 +44,25 @@ describe('adapter dynamic routes (no root params)', () => {
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"5 entries "5 entries
/$shellPrefix/posts/[id] /$1/posts/[id]
^[/]?/(?<shellPrefix>acme\\.one\\-two,three/de|acme\\.one\\-two,three/en)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(acme\\.one\\-two,three/de|acme\\.one\\-two,three/en)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /$shellPrefix/posts/[id]$rscSuffix?nxtPid=$nxtPid -> /$1/posts/[id]$3?nxtPid=$nxtPid
/acme.one-two,three/[locale]/posts/[id] /acme.one-two,three/[locale]/posts/[id]
^[/]?/acme\\.one\\-two,three/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/acme\\.one\\-two,three/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /acme.one-two,three/[locale]/posts/[id]$rscSuffix?nxtPlocale=$nxtPlocale&nxtPid=$nxtPid -> /acme.one-two,three/[locale]/posts/[id]$3?nxtPlocale=$nxtPlocale&nxtPid=$nxtPid
/sparse/en/posts/[id] /sparse/en/posts/[id]
^[/]?/sparse/en/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/sparse/en/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /sparse/en/posts/[id]$rscSuffix?nxtPid=$nxtPid -> /sparse/en/posts/[id]$2?nxtPid=$nxtPid
/sparse/[locale]/posts/[id] /sparse/[locale]/posts/[id]
^[/]?/sparse/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/sparse/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /sparse/[locale]/posts/[id]$rscSuffix?nxtPlocale=$nxtPlocale&nxtPid=$nxtPid -> /sparse/[locale]/posts/[id]$3?nxtPlocale=$nxtPlocale&nxtPid=$nxtPid
/[team]/[locale]/posts/[id] /[team]/[locale]/posts/[id]
^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[team]/[locale]/posts/[id]$rscSuffix?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid" -> /[team]/[locale]/posts/[id]$4?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid"
`) `)
}) })
}) })
...@@ -29,12 +29,12 @@ describe('adapter dynamic routes (shell prefixes, one combination)', () => { ...@@ -29,12 +29,12 @@ describe('adapter dynamic routes (shell prefixes, one combination)', () => {
"2 entries "2 entries
/acme.one-two,three/en/posts/[id] /acme.one-two,three/en/posts/[id]
^[/]?/acme\\.one\\-two,three/en/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/acme\\.one\\-two,three/en/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /acme.one-two,three/en/posts/[id]$rscSuffix?nxtPid=$nxtPid -> /acme.one-two,three/en/posts/[id]$2?nxtPid=$nxtPid
/[team]/[locale]/posts/[id] /[team]/[locale]/posts/[id]
^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[team]/[locale]/posts/[id]$rscSuffix?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid" -> /[team]/[locale]/posts/[id]$4?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid"
`) `)
}) })
}) })
...@@ -31,13 +31,13 @@ describe('adapter dynamic routes (shell prefixes)', () => { ...@@ -31,13 +31,13 @@ describe('adapter dynamic routes (shell prefixes)', () => {
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"2 entries "2 entries
/$shellPrefix/posts/[id] /$1/posts/[id]
^[/]?/(?<shellPrefix>acme\\.one\\-two,three/de|acme\\.one\\-two,three/en|sparse/en)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(acme\\.one\\-two,three/de|acme\\.one\\-two,three/en|sparse/en)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /$shellPrefix/posts/[id]$rscSuffix?nxtPid=$nxtPid -> /$1/posts/[id]$3?nxtPid=$nxtPid
/[team]/[locale]/posts/[id] /[team]/[locale]/posts/[id]
^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$ ^[/]?/(?<nxtPteam>[^/]+?)/(?<nxtPlocale>[^/]+?)/posts/(?<nxtPid>[^/]+?)(\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /[team]/[locale]/posts/[id]$rscSuffix?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid" -> /[team]/[locale]/posts/[id]$4?nxtPteam=$nxtPteam&nxtPlocale=$nxtPlocale&nxtPid=$nxtPid"
`) `)
}) })
}) })
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