Unverified Commit 21b9f6ba authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

fix: correct appPaths sort order for parallel routes with route groups (#91160)

### What?

Fixes webpack dev 404s when parallel routes have children nested inside
a route group (e.g. `@slot` + `(b1)/page`) and when a parallel route has
`page.tsx` directly inside it (e.g. `@slot/page.tsx`).

### Why?

Two separate issues caused 404s for parallel routes with route groups:

1. **Sort order**: The three `appPaths` sort sites used bare `.sort()`
(lexicographic ordering). `renderPageComponent` relies on
`appPaths[appPaths.length - 1]` being the children/root page. Without
route groups this works because `@` (0x40) sorts after lowercase letters
— `/@slot/page` comes before `/page`. But when the children page is
inside a route group, `(` (0x28) sorts before `@` (0x40), flipping the
order: `/(b1)/page < /@slot/page`. Now the last item is the slot page
instead of the children page, so the manifest lookup fails and a 404 is
returned.

2. **Double `__PAGE__` segment**: When a parallel route like `@slot` has
`page.tsx` directly inside it, `resolveParallelSegments` returns
`[PAGE_SEGMENT]` (an array) to signal that the loader should recurse
into the slot directory to pick up layout/default files. However, the
segment key normalization was mapping `PAGE_SEGMENT` to
`PAGE_SEGMENT_KEY` (`__PAGE__`), while the recursion would also produce
a `__PAGE__` for children — creating a double `__PAGE__` nesting (`slot:
['__PAGE__', { children: ['__PAGE__', ...] }, ...]`).

### How?

**Sort order fix**: Adds a `compareAppPaths` comparator in
`packages/next/src/shared/lib/router/utils/app-paths.ts` that sorts
paths containing `/@` segments before paths without them, ensuring the
children page is always last. Replaces the three bare `.sort()` calls
with `.sort(compareAppPaths)` in:

- `packages/next/src/build/entries.ts`
- `packages/next/src/server/lib/router-utils/setup-dev-bundler.ts`
-
`packages/next/src/server/route-matcher-providers/dev/dev-app-page-route-matcher-provider.ts`

**Loader tree fix**: Maps `PAGE_SEGMENT` to `'(slot)'` in the segment
key normalization (same as `PARALLEL_VIRTUAL_SEGMENT`), instead of
`PAGE_SEGMENT_KEY`. By the time this code is reached,
`parallelSegmentKey === PAGE_SEGMENT` only occurs for the array case
(the string case is handled by the early return), so this is safe. The
actual `__PAGE__` is correctly created by the recursion.

**Before:** `slot: ['__PAGE__', { children: ['__PAGE__', ...] }, ...]`
**After:** `slot: ['(slot)', { children: ['__PAGE__', ...] }, ...]`

Also adds an e2e test that verifies the fix across all modes (Turbopack
dev, Turbopack start, webpack dev).
parent 19ff1bab
...@@ -43,7 +43,10 @@ import { ...@@ -43,7 +43,10 @@ import {
} from './utils' } from './utils'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
compareAppPaths,
} from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
...@@ -417,7 +420,10 @@ export async function createEntrypoints( ...@@ -417,7 +420,10 @@ export async function createEntrypoints(
// Make sure to sort parallel routes to make the result deterministic. // Make sure to sort parallel routes to make the result deterministic.
appPathsPerRoute = Object.fromEntries( appPathsPerRoute = Object.fromEntries(
Object.entries(appPathsPerRoute).map(([k, v]) => [k, v.sort()]) Object.entries(appPathsPerRoute).map(([k, v]) => [
k,
v.sort(compareAppPaths),
])
) )
} }
......
...@@ -427,11 +427,10 @@ async function createTreeCodeFromPath( ...@@ -427,11 +427,10 @@ async function createTreeCodeFromPath(
// earlier logic (such as children$ and page$). These should never appear in the loader tree, and // earlier logic (such as children$ and page$). These should never appear in the loader tree, and
// should instead be the corresponding segment keys (ie `__PAGE__`) or the `children` parallel route. // should instead be the corresponding segment keys (ie `__PAGE__`) or the `children` parallel route.
parallelSegmentKey = parallelSegmentKey =
parallelSegmentKey === PARALLEL_VIRTUAL_SEGMENT parallelSegmentKey === PARALLEL_VIRTUAL_SEGMENT ||
parallelSegmentKey === PAGE_SEGMENT
? '(slot)' ? '(slot)'
: parallelSegmentKey === PAGE_SEGMENT : parallelSegmentKey
? PAGE_SEGMENT_KEY
: parallelSegmentKey
const normalizedParallelKey = normalizeParallelKey(parallelKey) const normalizedParallelKey = normalizeParallelKey(parallelKey)
let subtreeCode: string | undefined let subtreeCode: string | undefined
......
...@@ -94,7 +94,10 @@ import { ...@@ -94,7 +94,10 @@ import {
type RouteInfo, type RouteInfo,
type SlotInfo, type SlotInfo,
} from '../../../build/file-classifier' } from '../../../build/file-classifier'
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
compareAppPaths,
} from '../../../shared/lib/router/utils/app-paths'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash' import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
import { Lockfile, type DevServerInfo } from '../../../build/lockfile' import { Lockfile, type DevServerInfo } from '../../../build/lockfile'
import { deobfuscateText } from '../../../shared/lib/magic-identifier' import { deobfuscateText } from '../../../shared/lib/magic-identifier'
...@@ -951,7 +954,7 @@ async function startWatcher( ...@@ -951,7 +954,7 @@ async function startWatcher(
// Make sure to sort parallel routes to make the result deterministic. // Make sure to sort parallel routes to make the result deterministic.
serverFields.appPathRoutes = Object.fromEntries( serverFields.appPathRoutes = Object.fromEntries(
Object.entries(appPaths).map(([k, v]) => [k, v.sort()]) Object.entries(appPaths).map(([k, v]) => [k, v.sort(compareAppPaths)])
) )
await propagateServerField( await propagateServerField(
opts, opts,
......
...@@ -5,6 +5,7 @@ import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provid ...@@ -5,6 +5,7 @@ import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provid
import { DevAppNormalizers } from '../../normalizers/built/app' import { DevAppNormalizers } from '../../normalizers/built/app'
import { normalizeCatchAllRoutes } from '../../../build/normalize-catchall-routes' import { normalizeCatchAllRoutes } from '../../../build/normalize-catchall-routes'
import { compareAppPaths } from '../../../shared/lib/router/utils/app-paths'
export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppPageRouteMatcher> { export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppPageRouteMatcher> {
private readonly expression: RegExp private readonly expression: RegExp
...@@ -74,7 +75,7 @@ export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvide ...@@ -74,7 +75,7 @@ export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvide
// Make sure to sort parallel routes to make the result deterministic. // Make sure to sort parallel routes to make the result deterministic.
appPaths = Object.fromEntries( appPaths = Object.fromEntries(
Object.entries(appPaths).map(([k, v]) => [k, v.sort()]) Object.entries(appPaths).map(([k, v]) => [k, v.sort(compareAppPaths)])
) )
const matchers: Array<AppPageRouteMatcher> = [] const matchers: Array<AppPageRouteMatcher> = []
......
...@@ -51,6 +51,24 @@ export function normalizeAppPath(route: string) { ...@@ -51,6 +51,24 @@ export function normalizeAppPath(route: string) {
) )
} }
/**
* Comparator for sorting app paths so that parallel slot paths (containing
* `/@`) come before the children/root page path. This ensures the last item
* is always the children page, which is what `renderPageComponent` reads via
* `appPaths[appPaths.length - 1]`.
*
* Without this, route group prefixes like `(group)` (char code 0x28) sort
* before `@` (0x40), causing the children page to sort first instead of last
* and leading to a manifest mismatch / 404 in webpack dev mode.
*/
export function compareAppPaths(a: string, b: string): number {
const aHasSlot = a.includes('/@')
const bHasSlot = b.includes('/@')
if (aHasSlot && !bHasSlot) return -1
if (!aHasSlot && bHasSlot) return 1
return a.localeCompare(b)
}
/** /**
* Strips the `.rsc` extension if it's in the pathname. * Strips the `.rsc` extension if it's in the pathname.
* Since this function is used on full urls it checks `?` for searchParams handling. * Since this function is used on full urls it checks `?` for searchParams handling.
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>Home</p>
}
import { ReactNode } from 'react'
export default function ChildrenGroupLayout({
children,
}: {
children: ReactNode
}) {
return <div>{children}</div>
}
export default function ChildrenGroupPage() {
return (
<main>
<p id="children-page">Children (route group) page</p>
</main>
)
}
import { ReactNode } from 'react'
export default function SlotLayout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
export default function SlotPage() {
return <p id="slot-page">Slot Page</p>
}
import { ReactNode } from 'react'
export default function Layout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div>
<div id="slot">{slot}</div>
<div id="children">{children}</div>
</div>
)
}
/** @type {import('next').NextConfig} */
module.exports = {}
import { nextTestSetup } from 'e2e-utils'
describe('parallel-routes-group-depth', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render a page with a parallel slot and children in a route group', async () => {
const $ = await next.render$('/parallel-group-depths-shallow-slot-hole')
expect($('#slot-page').text()).toBe('Slot Page')
expect($('#children-page').text()).toBe('Children (route group) page')
})
})
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