Commit 753c96ba authored by Jimmy Lai's avatar Jimmy Lai

fix: preserve route group context in interception route rewrites (#67034)

When two route groups each define an intercepting route for the same
path (e.g., (group1)/@modal/(.)shared and (group2)/@modal/(.)shared),
both produce identical rewrite rules because normalizeAppPath strips
route group context. Only the first group's interception works.

This fix:
- Adds a denormalizedAppPaths parameter to generateInterceptionRoutesRewrites
  so the function can access route group context that's lost during
  normalization
- When multiple route groups map to the same normalized interception
  path, generates separate rewrites with more specific Next-Url header
  regexes based on sibling pages within each group
- Sorts rewrites by header regex specificity so more specific patterns
  are matched first
- Passes denormalized paths from build and dev server call sites

Note: the rewrite-level disambiguation is correct, but a separate build
issue causes both route group variants to be bundled with the same
component (the first group's). Full end-to-end fix requires additional
changes in the build pipeline's page deduplication logic.
parent 90841a5f
...@@ -1372,9 +1372,16 @@ export default async function build( ...@@ -1372,9 +1372,16 @@ export default async function build(
// eventually with the development code. // eventually with the development code.
validateAppPaths(appPaths) validateAppPaths(appPaths)
// Interception routes are modelled as beforeFiles rewrites // Interception routes are modelled as beforeFiles rewrites.
// Pass denormalized paths as third argument to preserve route group
// context for disambiguation when multiple groups intercept the
// same path (#67034).
rewrites.beforeFiles.push( rewrites.beforeFiles.push(
...generateInterceptionRoutesRewrites(appPaths, config.basePath) ...generateInterceptionRoutesRewrites(
appPaths,
config.basePath,
denormalizedAppPages
)
) )
NextBuildContext.rewrites = rewrites NextBuildContext.rewrites = rewrites
......
import type { Rewrite } from './load-custom-routes' import type { Rewrite } from './load-custom-routes'
import { generateInterceptionRoutesRewrites } from './generate-interception-routes-rewrites' import { generateInterceptionRoutesRewrites } from './generate-interception-routes-rewrites'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
/** /**
* Helper to create regex matchers from a rewrite object. * Helper to create regex matchers from a rewrite object.
...@@ -2064,38 +2065,50 @@ describe('generateInterceptionRoutesRewrites', () => { ...@@ -2064,38 +2065,50 @@ describe('generateInterceptionRoutesRewrites', () => {
// Should generate 3 rewrites, one for each interception route // Should generate 3 rewrites, one for each interception route
expect(rewrites).toHaveLength(3) expect(rewrites).toHaveLength(3)
// First rewrite: from /dashboard level // Find rewrites by destination (order may vary due to specificity sorting)
const dashboardRewrite = rewrites[0] const dashboardRewrite = rewrites.find(
(r) => r.destination === '/dashboard/@modal/(.)settings'
)!
const profileRewrite = rewrites.find(
(r) => r.destination === '/dashboard/profile/@modal/(..)settings'
)!
const rootRewrite = rewrites.find(
(r) => r.destination === '/@global-modal/(...)settings'
)!
expect(dashboardRewrite).toBeDefined()
expect(profileRewrite).toBeDefined()
expect(rootRewrite).toBeDefined()
// Dashboard rewrite: from /dashboard level
expect(dashboardRewrite.source).toBe('/dashboard/settings') expect(dashboardRewrite.source).toBe('/dashboard/settings')
expect(dashboardRewrite.destination).toBe(
'/dashboard/@modal/(.)settings'
)
const { headerRegex: dashboardHeader } = const { headerRegex: dashboardHeader } =
getRewriteMatchers(dashboardRewrite) getRewriteMatchers(dashboardRewrite)
expect(dashboardHeader.test('/dashboard')).toBe(true) expect(dashboardHeader.test('/dashboard')).toBe(true)
expect(dashboardHeader.test('/dashboard/profile')).toBe(true) expect(dashboardHeader.test('/dashboard/profile')).toBe(true)
// Second rewrite: from /dashboard/profile level (one level up) // Profile rewrite: from /dashboard/profile level (one level up)
const profileRewrite = rewrites[1]
expect(profileRewrite.source).toBe('/dashboard/settings') expect(profileRewrite.source).toBe('/dashboard/settings')
expect(profileRewrite.destination).toBe(
'/dashboard/profile/@modal/(..)settings'
)
const { headerRegex: profileHeader } = const { headerRegex: profileHeader } =
getRewriteMatchers(profileRewrite) getRewriteMatchers(profileRewrite)
expect(profileHeader.test('/dashboard/profile')).toBe(true) expect(profileHeader.test('/dashboard/profile')).toBe(true)
expect(profileHeader.test('/dashboard/profile/nested')).toBe(true) expect(profileHeader.test('/dashboard/profile/nested')).toBe(true)
// Third rewrite: from root level (...) // Root rewrite: from root level (...)
const rootRewrite = rewrites[2]
expect(rootRewrite.source).toBe('/settings') expect(rootRewrite.source).toBe('/settings')
expect(rootRewrite.destination).toBe('/@global-modal/(...)settings')
const { headerRegex: rootHeader } = getRewriteMatchers(rootRewrite) const { headerRegex: rootHeader } = getRewriteMatchers(rootRewrite)
expect(rootHeader.test('/')).toBe(true) expect(rootHeader.test('/')).toBe(true)
expect(rootHeader.test('/anything')).toBe(true) expect(rootHeader.test('/anything')).toBe(true)
// More specific rewrites should come before less specific ones
const dashboardIdx = rewrites.indexOf(dashboardRewrite)
const profileIdx = rewrites.indexOf(profileRewrite)
const rootIdx = rewrites.indexOf(rootRewrite)
expect(profileIdx).toBeLessThan(dashboardIdx)
expect(dashboardIdx).toBeLessThan(rootIdx)
}) })
it('should handle parallel routes with same target from different positions', () => { it('should handle parallel routes with same target from different positions', () => {
...@@ -2124,6 +2137,68 @@ describe('generateInterceptionRoutesRewrites', () => { ...@@ -2124,6 +2137,68 @@ describe('generateInterceptionRoutesRewrites', () => {
expect(header1.source).toBe(header2.source) expect(header1.source).toBe(header2.source)
expect(header1.test('/dashboard')).toBe(true) expect(header1.test('/dashboard')).toBe(true)
}) })
it('should disambiguate identical interception paths in different route groups (#67034)', () => {
// Two route groups each defining an intercepting route for the same path.
// In the real build/dev server, normalized paths are passed as the first
// argument and denormalized paths as the third.
const denormalized = [
'/(group1)/page',
'/(group1)/@modal/default',
'/(group1)/@modal/(.)shared/page',
'/(group2)/group2/page',
'/(group2)/@modal/default',
'/(group2)/@modal/(.)shared/page',
'/shared/page',
]
// Simulate what the build does: normalize and deduplicate
const normalized = [
...new Set(denormalized.map((p) => normalizeAppPath(p))),
]
const rewrites = generateInterceptionRoutesRewrites(
normalized,
'',
denormalized
)
// Should generate 2 rewrites (one per route group) instead of 1
const interceptionRewrites = rewrites.filter(
(r) => r.has && r.has.length > 0
)
expect(interceptionRewrites).toHaveLength(2)
// Both rewrites target the same normalized path
expect(interceptionRewrites[0].source).toBe('/shared')
expect(interceptionRewrites[1].source).toBe('/shared')
// The header regexes should be DIFFERENT to distinguish the groups
const matchers = interceptionRewrites.map((r) => getRewriteMatchers(r))
expect(matchers[0].headerRegex.source).not.toBe(
matchers[1].headerRegex.source
)
// Find the group2-specific rewrite (matches /group2)
const group2Idx = matchers.findIndex((m) =>
m.headerRegex.test('/group2')
)
const group1Idx = matchers.findIndex((_, i) => i !== group2Idx)
const group2Header = matchers[group2Idx].headerRegex
const group1Header = matchers[group1Idx].headerRegex
// Group2's regex should match /group2 (where group2's pages live)
expect(group2Header.test('/group2')).toBe(true)
expect(group2Header.test('/group2/subpage')).toBe(true)
// Group2's regex should NOT match / (group1's territory)
expect(group2Header.test('/')).toBe(false)
// Group1's regex should match / (where group1's pages live)
expect(group1Header.test('/')).toBe(true)
// Group2's more specific rewrite should come first (sorted by specificity)
expect(group2Idx).toBeLessThan(group1Idx)
})
}) })
describe('complex real-world integration patterns', () => { describe('complex real-world integration patterns', () => {
......
...@@ -2,21 +2,126 @@ import { NEXT_URL } from '../client/components/app-router-headers' ...@@ -2,21 +2,126 @@ import { NEXT_URL } from '../client/components/app-router-headers'
import { import {
extractInterceptionRouteInformation, extractInterceptionRouteInformation,
isInterceptionRouteAppPath, isInterceptionRouteAppPath,
INTERCEPTION_ROUTE_MARKERS,
} from '../shared/lib/router/utils/interception-routes' } from '../shared/lib/router/utils/interception-routes'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { isGroupSegment } from '../shared/lib/segment'
import type { Rewrite } from './load-custom-routes' import type { Rewrite } from './load-custom-routes'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
export function generateInterceptionRoutesRewrites( /**
appPaths: string[], * Extracts the route group prefix from a denormalized app path.
basePath = '' * This is the portion of the path before the interception marker,
): Rewrite[] { * with @-prefixed (parallel route) segments removed but route groups preserved.
const rewrites: Rewrite[] = [] *
* For example:
* `/(group1)/@modal/(.)shared/page` -> `/(group1)`
* `/(group2)/@modal/(.)shared/page` -> `/(group2)`
* `/@modal/(.)shared` -> null (no route group)
* `/foo/@modal/(.)bar` -> null (no route group)
*/
function getRouteGroupPrefix(appPath: string): string | null {
const segments = appPath.split('/')
const prefixSegments: string[] = []
let hasRouteGroup = false
for (const appPath of appPaths) { for (const segment of segments) {
if (isInterceptionRouteAppPath(appPath)) { // Stop when we hit the interception marker
const { interceptingRoute, interceptedRoute } = if (INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))) {
extractInterceptionRouteInformation(appPath) break
}
// Skip @-prefixed segments (parallel routes)
if (segment.startsWith('@')) {
continue
}
prefixSegments.push(segment)
if (segment && isGroupSegment(segment)) {
hasRouteGroup = true
}
}
if (!hasRouteGroup) {
return null
}
return prefixSegments.join('/') || '/'
}
/**
* Given a route group prefix (e.g., `/(group1)`), finds all non-interception
* page paths within that group from the full denormalized paths list,
* normalizes them to URL paths, and returns the longest common URL prefix.
*
* This is used to build a more specific Next-Url header regex for interception
* routes within route groups, so that two different groups intercepting the
* same path produce distinct rewrite rules.
*/
function findEffectiveInterceptingRoute(
routeGroupPrefix: string,
interceptingRoute: string,
denormalizedPaths: string[]
): string {
// Find all non-interception app paths under this route group prefix
const siblingUrls: string[] = []
// Normalize the prefix for matching (ensure it ends consistently)
const prefixForMatch = routeGroupPrefix === '/' ? '/' : routeGroupPrefix + '/'
for (const p of denormalizedPaths) {
if (isInterceptionRouteAppPath(p)) continue
// Check if this path is under the same route group
if (!p.startsWith(prefixForMatch) && p !== routeGroupPrefix) continue
// Skip default pages (@slot/default)
if (p.endsWith('/default')) continue
const normalized = normalizeAppPath(p)
if (normalized) {
siblingUrls.push(normalized)
}
}
if (siblingUrls.length === 0) {
return interceptingRoute
}
// Find the longest common prefix among sibling URLs
let commonPrefix = siblingUrls[0]
for (let i = 1; i < siblingUrls.length; i++) {
commonPrefix = longestCommonPrefix(commonPrefix, siblingUrls[i])
if (commonPrefix === '/') break
}
// Only use the common prefix if it's more specific than the original
// interceptingRoute (i.e., has more path segments)
if (commonPrefix.length > interceptingRoute.length) {
return commonPrefix
}
return interceptingRoute
}
function longestCommonPrefix(a: string, b: string): string {
let i = 0
while (i < a.length && i < b.length && a[i] === b[i]) {
i++
}
// Trim to the last complete path segment
const prefix = a.substring(0, i)
const lastSlash = prefix.lastIndexOf('/')
if (lastSlash <= 0) return '/'
return prefix.substring(0, lastSlash)
}
/**
* Given an interception route appPath and its extracted info, generates
* a single rewrite entry.
*/
function generateRewrite(
appPath: string,
interceptingRoute: string,
interceptedRoute: string,
basePath: string
): Rewrite {
const destination = getNamedRouteRegex(basePath + appPath, { const destination = getNamedRouteRegex(basePath + appPath, {
prefixRouteKeys: true, prefixRouteKeys: true,
}) })
...@@ -41,7 +146,7 @@ export function generateInterceptionRoutesRewrites( ...@@ -41,7 +146,7 @@ export function generateInterceptionRoutesRewrites(
// will match any descendants. // will match any descendants.
.replace(/\(\?:\/\)\?$/, '(?:/.*)?') .replace(/\(\?:\/\)\?$/, '(?:/.*)?')
rewrites.push({ return {
source: source.pathToRegexpPattern, source: source.pathToRegexpPattern,
destination: destination.pathToRegexpPattern, destination: destination.pathToRegexpPattern,
has: [ has: [
...@@ -52,9 +157,108 @@ export function generateInterceptionRoutesRewrites( ...@@ -52,9 +157,108 @@ export function generateInterceptionRoutesRewrites(
}, },
], ],
regex: source.namedRegex, regex: source.namedRegex,
}) }
}
export function generateInterceptionRoutesRewrites(
appPaths: string[],
basePath = '',
denormalizedAppPaths?: string[]
): Rewrite[] {
const rewrites: Rewrite[] = []
for (const appPath of appPaths) {
if (isInterceptionRouteAppPath(appPath)) {
const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(appPath)
// When denormalized paths are provided, check if multiple route groups
// map to this same normalized interception route. If so, generate a
// separate rewrite for each group with a more specific header regex.
// This fixes #67034 where two route groups intercepting the same path
// produced identical rewrites.
if (denormalizedAppPaths) {
// Find all denormalized paths that normalize to this appPath
const variants = denormalizedAppPaths.filter(
(p) => normalizeAppPath(p) === appPath
)
// Group variants by their route group prefix
const groupPrefixes = new Map<string | null, string[]>()
for (const variant of variants) {
const prefix = getRouteGroupPrefix(variant)
const existing = groupPrefixes.get(prefix)
if (existing) {
existing.push(variant)
} else {
groupPrefixes.set(prefix, [variant])
}
}
// If there are multiple distinct route groups, generate separate rewrites
if (groupPrefixes.size > 1) {
for (const [groupPrefix] of groupPrefixes) {
if (groupPrefix) {
const effectiveRoute = findEffectiveInterceptingRoute(
groupPrefix,
interceptingRoute,
denormalizedAppPaths
)
rewrites.push(
generateRewrite(
appPath,
effectiveRoute,
interceptedRoute,
basePath
)
)
} else {
// No route group - use standard intercepting route
rewrites.push(
generateRewrite(
appPath,
interceptingRoute,
interceptedRoute,
basePath
)
)
} }
} }
continue
}
// Single group prefix - check if it provides a more specific route
const singlePrefix = [...groupPrefixes.keys()][0]
if (singlePrefix) {
const effectiveRoute = findEffectiveInterceptingRoute(
singlePrefix,
interceptingRoute,
denormalizedAppPaths
)
rewrites.push(
generateRewrite(appPath, effectiveRoute, interceptedRoute, basePath)
)
continue
}
}
// Default: no denormalized paths or no route groups
rewrites.push(
generateRewrite(appPath, interceptingRoute, interceptedRoute, basePath)
)
}
}
// Sort rewrites so that more specific header regexes come first.
// This ensures that when multiple interception routes match the same
// source URL, the most specific one (based on the Next-Url header match)
// takes priority.
rewrites.sort((a, b) => {
const aHeader = a.has?.[0]?.value ?? ''
const bHeader = b.has?.[0]?.value ?? ''
// Longer regex patterns are typically more specific
return bHeader.length - aHeader.length
})
return rewrites return rewrites
} }
...@@ -659,9 +659,13 @@ export default class DevServer extends Server { ...@@ -659,9 +659,13 @@ export default class DevServer extends Server {
} }
protected getinterceptionRoutePatterns(): RegExp[] { protected getinterceptionRoutePatterns(): RegExp[] {
// Pass denormalized (original) paths as third argument to preserve
// route group context for disambiguation when multiple groups
// intercept the same path (#67034).
const rewrites = generateInterceptionRoutesRewrites( const rewrites = generateInterceptionRoutesRewrites(
Object.keys(this.appPathRoutes ?? {}), Object.keys(this.appPathRoutes ?? {}),
this.nextConfig.basePath this.nextConfig.basePath,
Object.values(this.appPathRoutes ?? {}).flat()
).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex)) ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))
if (this.nextConfig.output === 'export' && rewrites.length > 0) { if (this.nextConfig.output === 'export' && rewrites.length > 0) {
......
...@@ -978,9 +978,13 @@ async function startWatcher( ...@@ -978,9 +978,13 @@ async function startWatcher(
? getMiddlewareRouteMatcher(serverFields.middleware?.matchers) ? getMiddlewareRouteMatcher(serverFields.middleware?.matchers)
: undefined : undefined
// Pass denormalized (original) paths as third argument to preserve
// route group context for disambiguation when multiple route groups
// define intercepting routes for the same path (#67034).
const interceptionRoutes = generateInterceptionRoutesRewrites( const interceptionRoutes = generateInterceptionRoutesRewrites(
Object.keys(appPaths), Object.keys(appPaths),
opts.nextConfig.basePath opts.nextConfig.basePath,
Object.values(appPaths).flat()
).map((item) => ).map((item) =>
buildCustomRoute( buildCustomRoute(
'before_files_rewrite', 'before_files_rewrite',
......
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