Unverified Commit 6863a2bb authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Add build-time validation to detect ambiguous app routes (#85834)

## What

This PR introduces build-time validation to detect ambiguous app routes
that were previously going undetected until runtime.

## Why

Route conflicts could occur when different dynamic segment names (e.g.,
`[slug]` vs `[modalSlug]`) normalize to the same routing pattern. This
was particularly problematic for:

- Parallel routes with different parameter names that appeared to work
but had subtle conflicts
- Interception routes where structural equivalence wasn't being
validated
- Complex routing structures where the ambiguity only manifested at
runtime

These conflicts would slip through the build process and cause runtime
issues that were difficult to diagnose.

## How

Adds a new `validateAppPaths()` function that:

1. **Normalizes paths** to detect structural equivalence (e.g.,
`/blog/[slug]` and `/blog/[modalSlug]` both normalize to `/blog/[*]`)
2. **Validates individual paths** for syntax errors, duplicate slug
names, catch-all placement, and other issues
3. **Cross-validates paths** to detect ambiguous routes that would
conflict at runtime
4. **Provides clear error messages** with actionable guidance when
conflicts are detected

The validation is integrated into the build process in
`packages/next/src/build/index.ts` and runs automatically for all app
routes.

## Changes

- **New**: `validate-app-paths.ts` - Core validation logic with
comprehensive path normalization and conflict detection
- **New**: `validate-app-paths.test.ts` - Extensive test coverage (299
lines) covering valid configs, ambiguous routes, syntax errors, and edge
cases
- **Modified**: `build/index.ts` - Integration of validation into the
build process
- **Modified**: `get-segment-param.tsx` - Export `SegmentParam` type for
reuse

## Test Coverage

The test suite covers:
- Valid route configurations (different segments, depths, catch-all
patterns)
- Ambiguous route detection (parallel routes, different dynamic segment
names)
- Individual path validation (syntax errors, duplicate slugs, catch-all
placement)
- Edge cases (empty arrays, root routes, complex nested structures)
- Clear error messaging with actionable guidance
parent 4050a8a3
...@@ -907,5 +907,22 @@ ...@@ -907,5 +907,22 @@
"906": "Bindings not loaded yet, but they are being loaded, did you forget to await?", "906": "Bindings not loaded yet, but they are being loaded, did you forget to await?",
"907": "bindings not loaded yet. Either call `loadBindings` to wait for them to be available or ensure that `installBindings` has already been called.", "907": "bindings not loaded yet. Either call `loadBindings` to wait for them to be available or ensure that `installBindings` has already been called.",
"908": "Invalid flags should be run as node detached-flush dev ./path-to/project [eventsFile]", "908": "Invalid flags should be run as node detached-flush dev ./path-to/project [eventsFile]",
"909": "Failed to load SWC binary for %s/%s, see more info here: https://nextjs.org/docs/messages/failed-loading-swc" "909": "Failed to load SWC binary for %s/%s, see more info here: https://nextjs.org/docs/messages/failed-loading-swc",
"910": "Optional route parameters are not yet supported (\"%s\") in route \"%s\".",
"911": "You cannot use both a required and optional catch-all route at the same level in route \"%s\".",
"912": "Ambiguous app routes detected:\\n\\n%s\\n\\nThese routes cannot be distinguished from each other when matching URLs. Please ensure that dynamic segments have unique patterns or use different static segments.",
"913": "Optional catch-all must be the last part of the URL in route \"%s\".",
"914": "You cannot have the same slug name \"%s\" repeat within a single dynamic path in route \"%s\".",
"915": "Detected a three-dot character ('…') at ('%s') in route \"%s\". Did you mean ('...')?",
"916": "Segment names may not start or end with extra brackets ('%s') in route \"%s\".",
"917": "You cannot define a route with the same specificity as an optional catch-all route (\"%s\" and \"%s/[[...%s]]\").",
"918": "Catch-all must be the last part of the URL in route \"%s\".",
"919": "You cannot have the slug names \"%s\" and \"%s\" differ only by non-word symbols within a single dynamic path in route \"%s\".",
"920": "Segment names may not start with erroneous periods ('%s') in route \"%s\".",
"921": "Detected a three-dot character ('…') in parameter \"%s\" in route \"%s\". Did you mean ('...')?",
"922": "Parameter names cannot be empty in route \"%s\".",
"923": "%s is being parsed as a normalized route, but it has a route group or parallel route segment.",
"924": "Invalid interception route: %s",
"925": "You cannot define a route with the same specificity as an optional catch-all route (\"%s\" and \"/[[...%s]]\").",
"926": "Optional route parameters are not yet supported (\"[%s]\") in route \"%s\"."
} }
...@@ -230,6 +230,7 @@ import { ...@@ -230,6 +230,7 @@ import {
writeValidatorFile, writeValidatorFile,
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { Lockfile } from './lockfile' import { Lockfile } from './lockfile'
import { validateAppPaths } from './validate-app-paths'
type Fallback = null | boolean | string type Fallback = null | boolean | string
...@@ -1406,6 +1407,13 @@ export default async function build( ...@@ -1406,6 +1407,13 @@ export default async function build(
} }
const appPaths = Array.from(appPageKeys) const appPaths = Array.from(appPageKeys)
// Validate that the app paths are valid. This is currently duplicating
// the logic from packages/next/src/shared/lib/router/utils/sorted-routes.ts
// but is instead specifically focused on code that can be shared
// eventually with the development code.
validateAppPaths(appPaths)
// Interception routes are modelled as beforeFiles rewrites // Interception routes are modelled as beforeFiles rewrites
rewrites.beforeFiles.push( rewrites.beforeFiles.push(
...generateInterceptionRoutesRewrites(appPaths, config.basePath) ...generateInterceptionRoutesRewrites(appPaths, config.basePath)
......
This diff is collapsed.
import {
getParamProperties,
type SegmentParam,
} from '../shared/lib/router/utils/get-segment-param'
import {
isInterceptionAppRoute,
parseAppRoute,
type NormalizedAppRoute,
type NormalizedAppRouteSegment,
} from '../shared/lib/router/routes/app'
/**
* Validates segment parameters for common syntax errors.
* Based on validation logic from sorted-routes.ts
*/
function validateSegmentParam(param: SegmentParam, pathname: string): void {
// Check for empty parameter names
if (param.param.length === 0) {
throw new Error(`Parameter names cannot be empty in route "${pathname}".`)
}
// Check for three-dot character (…) instead of ...
if (param.param.includes('…')) {
throw new Error(
`Detected a three-dot character ('…') in parameter "${param.param}" in route "${pathname}". Did you mean ('...')?`
)
}
// Check for optional non-catch-all segments (not yet supported)
if (
param.type !== 'optional-catchall' &&
param.param.startsWith('[') &&
param.param.endsWith(']')
) {
throw new Error(
`Optional route parameters are not yet supported ("[${param.param}]") in route "${pathname}".`
)
}
// Check for extra brackets
if (param.param.startsWith('[') || param.param.endsWith(']')) {
throw new Error(
`Segment names may not start or end with extra brackets ('${param.param}') in route "${pathname}".`
)
}
// Check for erroneous periods
if (param.param.startsWith('.')) {
throw new Error(
`Segment names may not start with erroneous periods ('${param.param}') in route "${pathname}".`
)
}
}
/**
* Validates a Route object for internal consistency.
* Checks for duplicate slugs, invalid catch-all placement, and other route errors.
* For interception routes, validates both the intercepting and intercepted routes separately.
* Returns the validated segment parameters.
*/
function validateAppRoute(route: NormalizedAppRoute): void {
// For interception routes, validate the intercepting and intercepted routes separately
// This allows the same parameter name to appear in both parts
if (isInterceptionAppRoute(route)) {
validateAppRoute(route.interceptingRoute)
validateAppRoute(route.interceptedRoute)
return
}
// Then validate semantic constraints (duplicates, normalization, positioning)
const slugNames = new Set<string>()
const normalizedSegments = new Set<string>()
let hasCatchAll = false
let hasOptionalCatchAllInPath = false
let catchAllPosition = -1
for (let i = 0; i < route.segments.length; i++) {
const segment = route.segments[i]
// Type narrowing - only process dynamic segments
if (segment.type === 'dynamic') {
// First, validate syntax
validateSegmentParam(segment.param, route.pathname)
const properties = getParamProperties(segment.param.type)
if (properties.repeat) {
if (properties.optional) {
hasOptionalCatchAllInPath = true
} else {
hasCatchAll = true
}
catchAllPosition = i
}
// Check to see if the parameter name is already in use.
if (slugNames.has(segment.param.param)) {
throw new Error(
`You cannot have the same slug name "${segment.param.param}" repeat within a single dynamic path in route "${route.pathname}".`
)
}
// Normalize parameter name for comparison by removing all non-word
// characters.
const normalizedSegment = segment.param.param.replace(/\W/g, '')
if (normalizedSegments.has(normalizedSegment)) {
const existing = Array.from(slugNames).find((s) => {
return s.replace(/\W/g, '') === normalizedSegment
})
throw new Error(
`You cannot have the slug names "${existing}" and "${segment.param.param}" differ only by non-word symbols within a single dynamic path in route "${route.pathname}".`
)
}
slugNames.add(segment.param.param)
normalizedSegments.add(normalizedSegment)
}
// Check if catch-all is not at the end
if (hasCatchAll && i > catchAllPosition) {
throw new Error(
`Catch-all must be the last part of the URL in route "${route.pathname}".`
)
}
if (hasOptionalCatchAllInPath && i > catchAllPosition) {
throw new Error(
`Optional catch-all must be the last part of the URL in route "${route.pathname}".`
)
}
}
// Check for both required and optional catch-all
if (hasCatchAll && hasOptionalCatchAllInPath) {
throw new Error(
`You cannot use both a required and optional catch-all route at the same level in route "${route.pathname}".`
)
}
}
/**
* Validates a single path for internal consistency and returns its segment parameters.
*/
function parseAndValidateAppPath(path: string): NormalizedAppRoute {
// Fast parse the route information. We're expecting this to be a normalized
// route, so we pass `true` to the `parseAppRoute` function.
const route = parseAppRoute(path, true)
// Slow walk the data from the route in order to validate it.
validateAppRoute(route)
return route
}
/**
* Normalizes segments by replacing dynamic segment names with placeholders.
* This allows us to compare routes for structural equivalence.
* Preserves interception markers so that routes with different markers are not considered ambiguous.
*
* Examples:
* - [slug] -> [*]
* - [modalSlug] -> [*]
* - [...slug] -> [...*]
* - [[...slug]] -> [[...*]]
* - (..)test -> (..)test
* - (..)[slug] -> (..)[*]
*/
function normalizeSegments(
segments: readonly NormalizedAppRouteSegment[]
): string {
return (
'/' +
segments
.map((segment) => {
if (segment.type === 'static') {
return segment.name
}
// Dynamic segment - normalize the parameter name by replacing the
// parameter name with a wildcard. The interception marker is already
// included in the segment name, so no special handling is needed.
return segment.name.replace(segment.param.param, '*')
})
.join('/')
)
}
/**
* Validates that app paths don't create ambiguous routes.
*
* NOTE: The paths passed to this function should already have been normalized by normalizeAppPath,
* which means parallel route segments (@modal, @sidebar, etc.) have been removed.
*
* This function performs two types of validation:
* 1. Individual path validation (syntax, slug names, catch-all placement, etc.)
* 2. Cross-path validation (ambiguous routes, conflicting patterns)
*
* @param appPaths - Array of normalized app router paths to validate
* @returns Array of validated routes
* @throws Error if validation fails
*/
export function validateAppPaths(
appPaths: readonly string[]
): NormalizedAppRoute[] {
// First, validate each path individually
const paramsByPath = new Map<string, NormalizedAppRoute>()
for (const path of appPaths) {
paramsByPath.set(path, parseAndValidateAppPath(path))
}
// Group paths by their normalized structure for ambiguity detection
const structureMap = new Map<string, string[]>()
for (const [path, route] of paramsByPath) {
// Check if the last segment is an optional catch-all and check to see if
// there is a route with the same specificity that conflicts with it.
const lastSegment = route.segments[route.segments.length - 1]
if (
lastSegment?.type === 'dynamic' &&
lastSegment.param.type === 'optional-catchall'
) {
const prefixSegments = route.segments.slice(0, -1)
const normalizedPrefix = normalizeSegments(prefixSegments)
for (const [appPath, appRoute] of paramsByPath) {
const normalizedAppPath = normalizeSegments(appRoute.segments)
// Special case: root-level optional catch-all
// /[[...slug]] has prefix '' which should match '/'
if (prefixSegments.length === 0 && appPath === '/') {
throw new Error(
`You cannot define a route with the same specificity as an optional catch-all route ("${appPath}" and "/[[...${lastSegment.param.param}]]").`
)
}
// General case: compare normalized structures
if (normalizedAppPath === normalizedPrefix) {
throw new Error(
`You cannot define a route with the same specificity as an optional catch-all route ("${appPath}" and "${normalizedPrefix}/[[...${lastSegment.param.param}]]").`
)
}
}
}
// Normalize the route to get its structure
const structure = normalizeSegments(route.segments)
// Track which paths map to this structure
const existingPaths = structureMap.get(structure) ?? []
existingPaths.push(path)
structureMap.set(structure, existingPaths)
}
// Check for ambiguous routes (different slug names, same structure)
const conflicts: Array<{ paths: string[]; normalizedPath: string }> = []
for (const [structure, paths] of structureMap) {
if (paths.length > 1) {
// Multiple paths map to the same structure - this is ambiguous
conflicts.push({
paths,
normalizedPath: structure,
})
}
}
if (conflicts.length > 0) {
const errorMessages = conflicts.map(({ paths, normalizedPath }) => {
const pathsList = paths.map((p) => ` - ${p}`).join('\n')
return `Ambiguous route pattern "${normalizedPath}" matches multiple routes:\n${pathsList}`
})
throw new Error(
`Ambiguous app routes detected:\n\n${errorMessages.join('\n\n')}\n\n` +
`These routes cannot be distinguished from each other when matching URLs. ` +
`Please ensure that dynamic segments have unique patterns or use different static segments.`
)
}
return Array.from(paramsByPath.values())
}
import { InvariantError } from '../../invariant-error'
import { getSegmentParam, type SegmentParam } from '../utils/get-segment-param'
import {
INTERCEPTION_ROUTE_MARKERS,
type InterceptionMarker,
} from '../utils/interception-routes'
export type RouteGroupAppRouteSegment = {
type: 'route-group'
name: string
/**
* If present, this segment has an interception marker prefixing it.
*/
interceptionMarker?: InterceptionMarker
}
export type ParallelRouteAppRouteSegment = {
type: 'parallel-route'
name: string
/**
* If present, this segment has an interception marker prefixing it.
*/
interceptionMarker?: InterceptionMarker
}
export type StaticAppRouteSegment = {
type: 'static'
name: string
/**
* If present, this segment has an interception marker prefixing it.
*/
interceptionMarker?: InterceptionMarker
}
export type DynamicAppRouteSegment = {
type: 'dynamic'
name: string
param: SegmentParam
/**
* If present, this segment has an interception marker prefixing it.
*/
interceptionMarker?: InterceptionMarker
}
/**
* Represents a single segment in a route path.
* Can be either static (e.g., "blog") or dynamic (e.g., "[slug]").
*/
export type AppRouteSegment =
| StaticAppRouteSegment
| DynamicAppRouteSegment
| RouteGroupAppRouteSegment
| ParallelRouteAppRouteSegment
export type NormalizedAppRouteSegment =
| StaticAppRouteSegment
| DynamicAppRouteSegment
export function parseAppRouteSegment(segment: string): AppRouteSegment | null {
if (segment === '') {
return null
}
// Check if the segment starts with an interception marker
const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((m) =>
segment.startsWith(m)
)
const param = getSegmentParam(segment)
if (param) {
return {
type: 'dynamic',
name: segment,
param,
interceptionMarker,
}
} else if (segment.startsWith('(') && segment.endsWith(')')) {
return {
type: 'route-group',
name: segment,
interceptionMarker,
}
} else if (segment.startsWith('@')) {
return {
type: 'parallel-route',
name: segment,
interceptionMarker,
}
} else {
return {
type: 'static',
name: segment,
interceptionMarker,
}
}
}
export type AppRoute = {
normalized: boolean
pathname: string
segments: AppRouteSegment[]
dynamicSegments: DynamicAppRouteSegment[]
interceptionMarker: InterceptionMarker | undefined
interceptingRoute: AppRoute | undefined
interceptedRoute: AppRoute | undefined
}
export type NormalizedAppRoute = Omit<AppRoute, 'normalized' | 'segments'> & {
normalized: true
segments: NormalizedAppRouteSegment[]
}
export function isNormalizedAppRoute(
route: AppRoute
): route is NormalizedAppRoute {
return route.normalized
}
export type InterceptionAppRoute = Omit<
AppRoute,
'interceptionMarker' | 'interceptingRoute' | 'interceptedRoute'
> & {
interceptionMarker: InterceptionMarker
interceptingRoute: AppRoute
interceptedRoute: AppRoute
}
export type NormalizedInterceptionAppRoute = Omit<
InterceptionAppRoute,
| 'normalized'
| 'segments'
| 'interceptionMarker'
| 'interceptingRoute'
| 'interceptedRoute'
> & {
normalized: true
segments: NormalizedAppRouteSegment[]
interceptionMarker: InterceptionMarker
interceptingRoute: NormalizedAppRoute
interceptedRoute: NormalizedAppRoute
}
export function isInterceptionAppRoute(
route: NormalizedAppRoute
): route is NormalizedInterceptionAppRoute
export function isInterceptionAppRoute(
route: AppRoute
): route is InterceptionAppRoute {
return (
route.interceptionMarker !== undefined &&
route.interceptingRoute !== undefined &&
route.interceptedRoute !== undefined
)
}
export function parseAppRoute(
pathname: string,
normalized: true
): NormalizedAppRoute
export function parseAppRoute(pathname: string, normalized: false): AppRoute
export function parseAppRoute(
pathname: string,
normalized: boolean
): AppRoute | NormalizedAppRoute {
const pathnameSegments = pathname.split('/').filter(Boolean)
// Build segments array with static and dynamic segments
const segments: AppRouteSegment[] = []
// Parse if this is an interception route.
let interceptionMarker: InterceptionMarker | undefined
let interceptingRoute: AppRoute | NormalizedAppRoute | undefined
let interceptedRoute: AppRoute | NormalizedAppRoute | undefined
for (const segment of pathnameSegments) {
// Parse the segment into an AppSegment.
const appSegment = parseAppRouteSegment(segment)
if (!appSegment) {
continue
}
if (
normalized &&
(appSegment.type === 'route-group' ||
appSegment.type === 'parallel-route')
) {
throw new InvariantError(
`${pathname} is being parsed as a normalized route, but it has a route group or parallel route segment.`
)
}
segments.push(appSegment)
if (appSegment.interceptionMarker) {
const parts = pathname.split(appSegment.interceptionMarker)
if (parts.length !== 2) {
throw new Error(`Invalid interception route: ${pathname}`)
}
interceptingRoute = normalized
? parseAppRoute(parts[0], true)
: parseAppRoute(parts[0], false)
interceptedRoute = normalized
? parseAppRoute(parts[1], true)
: parseAppRoute(parts[1], false)
interceptionMarker = appSegment.interceptionMarker
}
}
const dynamicSegments = segments.filter(
(segment) => segment.type === 'dynamic'
)
return {
normalized,
pathname,
segments,
dynamicSegments,
interceptionMarker,
interceptingRoute,
interceptedRoute,
}
}
import { INTERCEPTION_ROUTE_MARKERS } from './interception-routes' import { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'
import type { DynamicParamTypes } from '../../app-router-types' import type { DynamicParamTypes } from '../../app-router-types'
export type SegmentParam = {
param: string
type: DynamicParamTypes
}
/** /**
* Parse dynamic route segment to type of parameter * Parse dynamic route segment to type of parameter
*/ */
export function getSegmentParam(segment: string): { export function getSegmentParam(segment: string): SegmentParam | null {
param: string
type: DynamicParamTypes
} | null {
const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker) => const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker) =>
segment.startsWith(marker) segment.startsWith(marker)
) )
......
...@@ -8,6 +8,8 @@ export const INTERCEPTION_ROUTE_MARKERS = [ ...@@ -8,6 +8,8 @@ export const INTERCEPTION_ROUTE_MARKERS = [
'(...)', '(...)',
] as const ] as const
export type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]
export function isInterceptionRouteAppPath(path: string): boolean { export function isInterceptionRouteAppPath(path: string): boolean {
// TODO-APP: add more serious validation // TODO-APP: add more serious validation
return ( return (
......
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