Unverified Commit 43c6ccfd authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Fix parallel routes ignoring generateStaticParams from primary route (#84889)

### What?

Fixes a bug where `generateStaticParams` from the primary route was
being ignored when dynamic segments existed in both regular routes
(`children`) and parallel routes (e.g., `@breadcrumbs`), causing routes
that should have been statically generated to return 404 errors.

Also fixes a related redirect loop issue that occurred when serving 404
pages with RSC request header validation enabled.

### Why?

**Primary Issue: Segment Deduplication**

The `collectAppPageSegments` function had two code paths for
deduplicating segments when the same dynamic parameter (like `[slug]`)
appeared in both the primary route tree and parallel routes:

1. **Individual segment processing** - Correctly preferred non-parallel
segments
2. **Batch processing at page boundaries** - Blindly overwrote existing
segments without preference checking

Due to BFS traversal order, parallel route segments would overwrite the
correct `children` route segments during batch processing. This marked
parameters as `isParallelRouteSegment: true`, which:
- Prevented the build system from recognizing them as regular route
parameters
- Caused `generateStaticParams` to be ignored during prerendering
- Resulted in all routes being treated as dynamic-only (404s with
`dynamicParams = false`)

This violated the architectural invariant that parallel routes are
"secondary" to the main route hierarchy - the primary route tree should
determine URL structure and static generation behavior.

**Secondary Issue: 404 Page Redirect Loop**

When serving a 404 page (NoFallbackError), the experimental RSC request
header validation would cause an infinite redirect loop. This happened
because:
- Headers are already stripped when serving the 404 page
- The validation comparison would always fail
- This triggered a redirect, which would hit the same 404, creating a
loop

### How?

**Segment Preference Fix (`app-segments.ts`):**

Applied consistent segment preference logic to both deduplication code
paths in `collectAppPageSegments` and `collectFallbackRouteParams`,
ensuring segments from the `children` route are always preferred over
parallel route segments. This preserves the following guarantees:

1. **URL structure is determined by the primary route tree** - Parallel
routes derive their parameters from `children`, not vice versa
2. **`generateStaticParams` works correctly** - Static generation is
controlled by the primary route's configuration
3. **Parallel routes remain decorative** - They enhance the page without
affecting core routing behavior

**Redirect Loop Fix (`base-server.ts`):**

Skip RSC request header validation when serving 404 pages (`!is404Page`
condition), preventing the redirect loop caused by already-stripped
headers failing the validation check.

**Test Coverage:**

Added comprehensive e2e test suite covering:
- Root parameters with `generateStaticParams` and `dynamicParams =
false`
- Dynamic child routes with and without `generateStaticParams`
- Parallel route slots with shared dynamic segments
- Prefetch behavior to ensure no redirect loops during preloading

Fixes #

NAR-446
parent a5064d7e
......@@ -128,10 +128,12 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
// If this is a page segment, we've reached a leaf node
if (name === PAGE_SEGMENT_KEY) {
// Add all segments in the current path
// Add all segments in the current path, preferring non-parallel segments
updatedSegments.forEach((seg) => {
const key = getSegmentKey(seg)
uniqueSegments.set(key, seg)
if (!uniqueSegments.has(key)) {
uniqueSegments.set(key, seg)
}
})
}
......@@ -152,7 +154,7 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
}
function getSegmentKey(segment: AppSegment) {
return `${segment.name}-${segment.filePath ?? ''}-${segment.paramName ?? ''}`
return `${segment.name}-${segment.filePath ?? ''}-${segment.paramName ?? ''}-${segment.isParallelRouteSegment ? 'pr' : 'np'}`
}
/**
......@@ -244,7 +246,7 @@ export function collectFallbackRouteParams(
// Handle this segment (if it's a dynamic segment param).
const segmentParam = getSegmentParam(name)
if (segmentParam) {
const key = `${name}-${segmentParam.param}`
const key = `${name}-${segmentParam.param}-${isParallelRouteSegment ? 'pr' : 'np'}`
if (!uniqueSegments.has(key)) {
uniqueSegments.set(
key,
......
......@@ -793,12 +793,29 @@ export async function buildAppStaticPaths({
// we're emitting the route for the base route.
const parallelFallbackRouteParams: FallbackRouteParam[] = []
// First pass: collect all non-parallel route param names.
// This allows us to filter out parallel route params that duplicate non-parallel ones.
const nonParallelParamNames = new Set<string>()
for (const segment of segments) {
if (!segment.paramName || !segment.paramType) continue
if (!segment.isParallelRouteSegment) {
nonParallelParamNames.add(segment.paramName)
}
}
// Second pass: collect segments, ensuring non-parallel route params take precedence.
for (const segment of segments) {
// If this segment doesn't have a param name then it's not param that we
// need to resolve.
if (!segment.paramName || !segment.paramType) continue
if (segment.isParallelRouteSegment) {
// Skip parallel route params that are already defined as non-parallel route params.
// Non-parallel route params take precedence because they appear in the URL pathname.
if (nonParallelParamNames.has(segment.paramName)) {
continue
}
// Collect all the parallel route segments that have dynamic params for
// second-pass resolution.
parallelRouteSegments.push({
......
......@@ -2015,7 +2015,11 @@ export default abstract class Server<
if (
!this.minimalMode &&
this.nextConfig.experimental.validateRSCRequestHeaders &&
isRSCRequest
isRSCRequest &&
// In the event that we're serving a NoFallbackError, the headers will
// already be stripped so this comparison will always fail, resulting in
// a redirect loop.
!is404Page
) {
const headers = req.headers
......
export default function BreadcrumbsDefault() {
return <div id="breadcrumbs-default">Breadcrumbs: (default)</div>
}
export default async function BreadcrumbsStoryPage({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
return (
<div id="breadcrumbs-story">
<div id="breadcrumbs-locale">Breadcrumbs Locale: {locale}</div>
<div id="breadcrumbs-slug">Breadcrumbs Story: {slug}</div>
</div>
)
}
import type { ReactNode } from 'react'
export default function RootLayout({
children,
breadcrumbs,
}: {
children: ReactNode
breadcrumbs: ReactNode
params: Promise<{ locale: string }>
}) {
return (
<>
<div id="breadcrumbs">{breadcrumbs}</div>
<main id="main">{children}</main>
</>
)
}
export default async function StoryPage({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
return (
<div id="story-page">
<div id="story-locale">Locale: {locale}</div>
<div id="story-slug">Story: {slug}</div>
</div>
)
}
export async function generateStaticParams() {
return [{ slug: 'static-123' }]
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
type RouteInfo = {
href: string
status: '200' | '404'
}
type RouteSection = {
title: string
columns: string[]
routes: RouteInfo[]
}
const ROUTE_SECTIONS: RouteSection[] = [
{
title: 'Base Routes',
columns: ['Route', 'Expected Status'],
routes: [
{ href: '/en', status: '200' },
{ href: '/fr', status: '200' },
{ href: '/es', status: '404' },
],
},
{
title: 'Without generateStaticParams',
columns: ['Route', 'Expected Status'],
routes: [
{ href: '/en/no-gsp/stories/dynamic-123', status: '200' },
{ href: '/fr/no-gsp/stories/dynamic-123', status: '200' },
{ href: '/es/no-gsp/stories/dynamic-123', status: '200' },
],
},
{
title: 'With generateStaticParams',
columns: ['Route', 'Expected Status'],
routes: [
{
href: '/en/gsp/stories/static-123',
status: '200',
},
{
href: '/fr/gsp/stories/static-123',
status: '200',
},
{
href: '/es/gsp/stories/static-123',
status: '404',
},
{
href: '/en/gsp/stories/dynamic-123',
status: '404',
},
{
href: '/fr/gsp/stories/dynamic-123',
status: '404',
},
{
href: '/es/gsp/stories/dynamic-123',
status: '404',
},
],
},
]
function NavLink({ href, status }: { href: string; status: '200' | '404' }) {
return (
<Link
href={href}
className={`font-mono text-xs hover:underline ${status === '200' ? 'text-green-700' : 'text-red-700'}`}
>
{href}
</Link>
)
}
function StatusBadge({ status }: { status: '200' | '404' }) {
return (
<span
className={`inline-block px-1 py-0 rounded text-xs ${status === '200' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}
>
{status}
</span>
)
}
function RouteTable({ section }: { section: RouteSection }) {
return (
<div>
<h2 className="text-sm font-bold mb-1">{section.title}</h2>
<table className="w-full border-collapse border border-gray-300 text-xs">
<thead>
<tr className="bg-gray-100">
{section.columns.map((column) => (
<th
key={column}
className="border border-gray-300 px-2 py-0.5 text-left w-1/2"
>
{column}
</th>
))}
</tr>
</thead>
<tbody>
{section.routes.map((route) => (
<tr key={route.href}>
<td className="border border-gray-300 px-2 py-0.5">
<NavLink href={route.href} status={route.status} />
</td>
<td className="border border-gray-300 px-2 py-0.5">
<StatusBadge status={route.status} />
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
export default function Navigation() {
const [revealed, setRevealed] = useState(false)
return (
<>
<input
id="reveal"
type="checkbox"
checked={revealed}
onChange={() => setRevealed(!revealed)}
/>
{revealed && (
<nav id="nav" className="space-y-2">
{ROUTE_SECTIONS.map((section) => (
<RouteTable key={section.title} section={section} />
))}
</nav>
)}
</>
)
}
import type { ReactNode } from 'react'
import Navigation from './layout.client'
export function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'fr' }]
}
export const dynamicParams = false
export default function RootLayout({
children,
}: {
children: ReactNode
params: Promise<{ locale: string }>
}) {
return (
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body className="p-2 flex flex-col gap-2 text-sm">
<Navigation />
{children}
</body>
</html>
)
}
export default function BreadcrumbsDefault() {
return <div id="breadcrumbs-default">Breadcrumbs: (default)</div>
}
export default async function BreadcrumbsStoryPage({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
return (
<div id="breadcrumbs-story">
<div id="breadcrumbs-locale">Breadcrumbs Locale: {locale}</div>
<div id="breadcrumbs-slug">Breadcrumbs Story: {slug}</div>
</div>
)
}
import type { ReactNode } from 'react'
export default function RootLayout({
children,
breadcrumbs,
}: {
children: ReactNode
breadcrumbs: ReactNode
params: Promise<{ locale: string }>
}) {
return (
<>
<div id="breadcrumbs">{breadcrumbs}</div>
<main id="main">{children}</main>
</>
)
}
export default async function StoryPage({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
return (
<div id="story-page">
<div id="story-locale">Locale: {locale}</div>
<div id="story-slug">Story: {slug}</div>
</div>
)
}
export default async function LocalePage({
params,
}: {
params: Promise<{ locale: string }>
}) {
const { locale } = await params
return <div id="locale-page">Locale: {locale}</div>
}
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import { setTimeout } from 'node:timers/promises'
describe('parallel-routes-root-param-dynamic-child', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
async function createBrowserActor(url: string, errorPage: boolean = false) {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser(url, {
beforePageLoad(page) {
act = createRouterAct(page, { allowErrorStatusCodes: [404] })
},
// throttling the CPU to rule out flakiness based on how quickly the page loads
cpuThrottleRate: 6,
})
// If we're on the error page, we don't have a nav element to wait for.
if (errorPage) {
return { act, browser }
}
// The page has navigation links that will be automatically prefetched.
// Some routes will 404 (like /es which isn't in generateStaticParams),
// so we allow 404 status codes. Let's reveal the navigation links and let
// the prefetching occur.
await act(
async () => {
await browser.elementByCss('#reveal').click()
// Ensure the navigation is visible
await browser.elementByCss('#nav')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
// Scroll to bottom to ensure all links enter viewport and trigger prefetches
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
},
// If we're in development, we don't have any prefetching to wait for.
isNextDev ? 'no-requests' : undefined
)
return { act, browser }
}
if (!isNextDev) {
describe('Prefetching', () => {
it('prefetches the 404 pages correctly', async () => {
await createBrowserActor('/en')
// If we got here without errors, the prefetch responses completed successfully
// without problematic redirects (like 307). Those will throw because
// it'll hit the net::ERR_TOO_MANY_REDIRECTS error.
})
})
}
describe('Base Routes', () => {
it.each(['en', 'fr'])(
'should render a 200 for /%s (in generateStaticParams)',
async (locale) => {
const { browser } = await createBrowserActor(`/${locale}`)
expect(await browser.elementByCss('#locale-page').text()).toBe(
`Locale: ${locale}`
)
}
)
it('should render a 404 for /es (not in generateStaticParams)', async () => {
const { browser } = await createBrowserActor('/es', true)
expect(await browser.elementByCss('.next-error-h1').text()).toBe('404')
})
})
describe('Without generateStaticParams (no-gsp)', () => {
it.each(['en', 'fr', 'es'])(
'should render a 200 for /%s/no-gsp/stories/dynamic-123',
async (locale) => {
const { browser, act } = await createBrowserActor('/en')
await act(async () => {
await browser
.elementByCss(`[href="/${locale}/no-gsp/stories/dynamic-123"]`)
.click()
})
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: dynamic-123'
)
}
)
it('should allow dynamic params even with /es locale', async () => {
// Even though /es is not in the root generateStaticParams,
// no-gsp routes should still work because they don't enforce static params
const { browser } = await createBrowserActor(
'/es/no-gsp/stories/dynamic-123'
)
expect(await browser.elementByCss('#story-locale').text()).toBe(
'Locale: es'
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: dynamic-123'
)
})
})
describe('With generateStaticParams (gsp)', () => {
describe('Static params (static-123)', () => {
it.each(['en', 'fr'])(
'should render a 200 for /%s/gsp/stories/static-123',
async (locale) => {
const { browser, act } = await createBrowserActor(`/${locale}`)
await act(async () => {
await browser
.elementByCss(`[href="/${locale}/gsp/stories/static-123"]`)
.click()
})
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: static-123'
)
}
)
it('should render a 404 for /es/gsp/stories/static-123 (locale not in generateStaticParams)', async () => {
const response = await next.fetch('/es/gsp/stories/static-123')
expect(response.status).toBe(404)
})
})
describe('Dynamic params (dynamic-123)', () => {
it.each(['en', 'fr'])(
'should render a 404 for /%s/gsp/stories/dynamic-123 (slug not in generateStaticParams)',
async (locale) => {
const { browser, act } = await createBrowserActor(`/${locale}`)
await act(async () => {
await browser
.elementByCss(`[href="/${locale}/gsp/stories/dynamic-123"]`)
.click()
})
expect(await browser.elementByCss('.next-error-h1').text()).toBe(
'404'
)
}
)
it('should render a 404 for /es/gsp/stories/dynamic-123 (both locale and slug not allowed)', async () => {
const response = await next.fetch('/es/gsp/stories/dynamic-123')
expect(response.status).toBe(404)
})
})
})
})
......@@ -361,7 +361,8 @@
"test/production/app-dir/unexpected-error/unexpected-error.test.ts",
"test/production/app-dir/worker-restart/worker-restart.test.ts",
"test/production/app-dir/resume-data-cache/resume-data-cache.test.ts",
"test/production/app-dir/unstable-cache-foreground-revalidate/unstable-cache-foreground-revalidate.test.ts"
"test/production/app-dir/unstable-cache-foreground-revalidate/unstable-cache-foreground-revalidate.test.ts",
"test/e2e/app-dir/parallel-routes-root-param-dynamic-child/parallel-routes-root-param-dynamic-child.test.ts"
]
}
}
......@@ -57,8 +57,45 @@ type ActConfig =
| null
export function createRouterAct(
page: Playwright.Page
page: Playwright.Page,
options?: {
/**
* Status codes that are allowed to be returned by the server. If not
* provided, all error status codes are disallowed (400+).
*/
allowErrorStatusCodes?: number[]
}
): <T>(scope: () => Promise<T> | T, config?: ActConfig) => Promise<T> {
/**
* Helper function to wait for requestIdleCallback with retry logic.
* Retries up to 3 times if "Execution context was destroyed" error occurs.
*/
async function waitForIdleCallback(): Promise<void> {
const maxRetries = 3
const retryDelayMs = 100
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
await page.evaluate(
() => new Promise<void>((res) => requestIdleCallback(() => res()))
)
return
} catch (err) {
const isLastAttempt = attempt === maxRetries - 1
const isExecutionContextError =
err instanceof Error &&
err.message.includes('Execution context was destroyed')
if (isExecutionContextError && !isLastAttempt) {
await new Promise((resolve) => setTimeout(resolve, retryDelayMs))
continue
}
throw err
}
}
}
/**
* Test utility for requests initiated by the Next.js Router, such as
* prefetches and navigations. Calls the given async function then intercepts
......@@ -79,6 +116,8 @@ export function createRouterAct(
let expectedResponses: Array<ExpectedResponseConfig> | null
let forbiddenResponses: Array<ExpectedResponseConfig> | null = null
let shouldBlockAll = false
const allowStatuses = options?.allowErrorStatusCodes ?? null
if (config === undefined || config === null) {
// Default. Expect at least one request, but don't assert on the response.
expectedResponses = []
......@@ -230,7 +269,7 @@ export function createRouterAct(
}
currentBatch = batch
await page.route('**/*', routeHandler)
await page.on('framedetached', hardNavigationHandler)
page.on('framedetached', hardNavigationHandler)
try {
// Call the user-provided scope function
const returnValue = await scope()
......@@ -258,9 +297,7 @@ export function createRouterAct(
// We use requestIdleCallback to schedule the task because that's
// guaranteed to fire after any IntersectionObserver events, which the
// router uses to track the visibility of links.
await page.evaluate(
() => new Promise<void>((res) => requestIdleCallback(() => res()))
)
await waitForIdleCallback()
// Checking whether a request needs to be intercepted is an async
// operation, so we need to wait for all the checks to complete before
......@@ -298,7 +335,11 @@ ${fulfilled.body}
throw error
}
if (fulfilled.status >= 400) {
if (
fulfilled.status >= 400 &&
(allowStatuses === null ||
!allowStatuses.includes(fulfilled.status))
) {
error.message = `
Received a response with an error status code.
......@@ -400,7 +441,11 @@ ${fulfilled.body}
})
const browserResponse = await request.response()
if (browserResponse !== null) {
await browserResponse.finished()
// For error responses (>= 400), the browser may not consume the body
// in the same way, so we skip waiting for finished() to avoid hanging
if (fulfilled.status < 400) {
await browserResponse.finished()
}
}
}
}
......@@ -417,7 +462,7 @@ ${fulfilled.body}
// a strategy to make that work. In the meantime, attempting to
// write a test that blocks a redirect will result in an error
// (see error above).
await new Promise<void>((resolve) => {
await new Promise<void>((resolve, reject) => {
page.once('request', (req) => {
const handleResponse = (res: Playwright.Response) => {
if (res.url() === req.url()) {
......@@ -426,8 +471,10 @@ ${fulfilled.body}
route: null,
result: (async () => {
return {
text: await res.text(),
body: await res.body(),
// For redirects, body may not be available, so catch
// the error and return an empty string.
text: await res.text().catch(() => ''),
body: await res.body().catch(() => Buffer.from('')),
headers: res.headers(),
status: res.status(),
}
......@@ -435,10 +482,20 @@ ${fulfilled.body}
didProcess: false,
})
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
resolve()
}
}
const handleFailure = (failedReq: Playwright.Request) => {
if (failedReq.url() === req.url()) {
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
error.message = `Request failed: ${failedReq.failure()?.errorText || 'Unknown error'}\n\nURL: ${req.url()}`
reject(error)
}
}
page.on('response', handleResponse)
page.on('requestfailed', handleFailure)
})
})
}
......@@ -450,9 +507,7 @@ ${fulfilled.body}
// network throttled, the next request is issued either directly within
// the task of the previous request's completion event, or in the
// microtask queue of that event.
await page.evaluate(
() => new Promise<void>((res) => requestIdleCallback(() => res()))
)
await waitForIdleCallback()
await waitForPendingRequestChecks()
}
......@@ -503,7 +558,7 @@ ${fulfilled.body}
// Clean up
currentBatch = prevBatch
await page.unroute('**/*', routeHandler)
await page.off('framedetached', hardNavigationHandler)
page.off('framedetached', hardNavigationHandler)
}
}
......
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