Unverified Commit 26bf404d authored by Josh Story's avatar Josh Story Committed by GitHub

Enable strict route matching by default (#97397)

## Summary

This enables strict route matching by default. App Router URLs that
cannot construct a complete route tree are rejected, unreachable pages
are reported, and incomplete catch-all matchers are pruned.

If strict route matching finds one of these invalid route structures,
Next.js warns that the validation implies a bug in the app and points to
`deprecated.looseRouteMatching: true` as a temporary escape hatch. The
deprecated option only accepts `true`; strict matching remains the
normalized internal behavior when the option is absent.

For example, this layout cannot render either URL as a complete route
because neither named slot has a page or default for the URL matched by
its sibling:

```text
app/
├── layout.tsx
├── @left/foo/page.tsx
└── @right/bar/page.tsx
```

Previously the app could depend on soft navigation preserving stale slot
state even though `/foo` and `/bar` could not be loaded directly. With
strict route matching enabled, the build reports the incompatible slots
and the two unreachable pages. Adding explicit defaults makes the
intended fallback behavior valid again.

## Verification

- `pnpm build-all`
- `pnpm exec jest packages/next/src/server/config.test.ts --runInBand`
- `parallel-routes-pruned-matchers` in production with Turbopack and
Webpack
- `parallel-routes-leaf-segments` in production with Turbopack
- strict diagnostic fixtures in production with Turbopack

<!-- NEXT_JS_LLM -->
parent e7d9685d
...@@ -64,6 +64,8 @@ import { MissingCanonicalInterceptionRoutesError } from '../shared/lib/errors/mi ...@@ -64,6 +64,8 @@ import { MissingCanonicalInterceptionRoutesError } from '../shared/lib/errors/mi
import { IncompatibleParallelRouteSlotsError } from '../shared/lib/errors/incompatible-parallel-route-slots-error' import { IncompatibleParallelRouteSlotsError } from '../shared/lib/errors/incompatible-parallel-route-slots-error'
import { findMissingCanonicalInterceptionRoutes } from '../shared/lib/router/utils/interception-routes' import { findMissingCanonicalInterceptionRoutes } from '../shared/lib/router/utils/interception-routes'
import { findPageFile } from '../server/lib/find-page-file' import { findPageFile } from '../server/lib/find-page-file'
import * as Log from './output/log'
import { getStrictRouteMatchingDefaultWarning } from '../server/lib/router-utils/strict-route-matching-config'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts' import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
...@@ -508,6 +510,12 @@ export async function createEntrypoints( ...@@ -508,6 +510,12 @@ export async function createEntrypoints(
) )
) )
} }
if (routeMatchingErrors.length > 0) {
const warning = getStrictRouteMatchingDefaultWarning(config)
if (warning) {
Log.warnOnce(warning)
}
}
if (routeMatchingErrors.length === 1) { if (routeMatchingErrors.length === 1) {
throw routeMatchingErrors[0] throw routeMatchingErrors[0]
} }
......
import { formatIssue, isRelevantWarning } from '../shared/lib/turbopack/utils' import {
formatIssue,
isRelevantWarning,
renderStyledStringToErrorAnsi,
} from '../shared/lib/turbopack/utils'
import type { TurbopackResult } from './swc/types' import type { TurbopackResult } from './swc/types'
import * as Log from './output/log'
const STRICT_ROUTE_MATCHING_ISSUE_TITLES = new Set([
'Interception routes must have a canonical route',
'Parallel route slots cannot render the same URLs',
'Unmatched app pages',
])
export function formatWarningsHeader(count: number): string { export function formatWarningsHeader(count: number): string {
return `Turbopack build encountered ${count} ${count === 1 ? 'warning' : 'warnings'}:` return `Turbopack build encountered ${count} ${count === 1 ? 'warning' : 'warnings'}:`
...@@ -19,7 +30,10 @@ export function formatWarningsHeader(count: number): string { ...@@ -19,7 +30,10 @@ export function formatWarningsHeader(count: number): string {
export function printBuildErrors<T>( export function printBuildErrors<T>(
result: TurbopackResult<T>, result: TurbopackResult<T>,
isDev: boolean, isDev: boolean,
opts?: { deferWarnings?: boolean } opts?: {
deferWarnings?: boolean
strictRouteMatchingDefaultWarning?: string
}
): { warnings: string[] } { ): { warnings: string[] } {
// Issues that we want to stop the server from executing // Issues that we want to stop the server from executing
const topLevelFatalIssues = [] const topLevelFatalIssues = []
...@@ -32,8 +46,18 @@ export function printBuildErrors<T>( ...@@ -32,8 +46,18 @@ export function printBuildErrors<T>(
const seenFatalIssues = new Set<string>() const seenFatalIssues = new Set<string>()
const seenErrors = new Set<string>() const seenErrors = new Set<string>()
const seenWarnings = new Set<string>() const seenWarnings = new Set<string>()
let hasStrictRouteMatchingIssue = false
for (const issue of result.issues) { for (const issue of result.issues) {
if (
issue.severity === 'error' &&
STRICT_ROUTE_MATCHING_ISSUE_TITLES.has(
renderStyledStringToErrorAnsi(issue.title)
)
) {
hasStrictRouteMatchingIssue = true
}
// We only want to completely shut down the server // We only want to completely shut down the server
if (issue.severity === 'fatal' || issue.severity === 'bug') { if (issue.severity === 'fatal' || issue.severity === 'bug') {
const formatted = formatIssue(issue) const formatted = formatIssue(issue)
...@@ -83,6 +107,10 @@ export function printBuildErrors<T>( ...@@ -83,6 +107,10 @@ export function printBuildErrors<T>(
) )
} }
if (hasStrictRouteMatchingIssue && opts?.strictRouteMatchingDefaultWarning) {
Log.warnOnce(opts.strictRouteMatchingDefaultWarning)
}
if (topLevelFatalIssues.length > 0) { if (topLevelFatalIssues.length > 0) {
throw new Error( throw new Error(
`Turbopack build failed with ${ `Turbopack build failed with ${
......
...@@ -20,6 +20,7 @@ import { printBuildErrors } from '../print-build-errors' ...@@ -20,6 +20,7 @@ import { printBuildErrors } from '../print-build-errors'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import type { ProjectOptions, RawEntrypoints } from '../swc/types' import type { ProjectOptions, RawEntrypoints } from '../swc/types'
import { Bundler } from '../../lib/bundler' import { Bundler } from '../../lib/bundler'
import { getStrictRouteMatchingDefaultWarning } from '../../server/lib/router-utils/strict-route-matching-config'
export async function turbopackBuild(telemetry: Telemetry): Promise<{ export async function turbopackBuild(telemetry: Telemetry): Promise<{
duration: number duration: number
...@@ -184,6 +185,8 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{ ...@@ -184,6 +185,8 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
// keeping SSG errors more prominent than compile warnings. // keeping SSG errors more prominent than compile warnings.
const { warnings } = printBuildErrors(entrypoints, dev, { const { warnings } = printBuildErrors(entrypoints, dev, {
deferWarnings: true, deferWarnings: true,
strictRouteMatchingDefaultWarning:
getStrictRouteMatchingDefaultWarning(config),
}) })
// Skip when telemetry is fully off — featureUsage() isn't free. // Skip when telemetry is fully off — featureUsage() isn't free.
......
...@@ -644,6 +644,11 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -644,6 +644,11 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
crossOrigin: z crossOrigin: z
.union([z.literal('anonymous'), z.literal('use-credentials')]) .union([z.literal('anonymous'), z.literal('use-credentials')])
.optional(), .optional(),
deprecated: z
.strictObject({
looseRouteMatching: z.literal(true).optional(),
})
.optional(),
deploymentId: z.string().optional(), deploymentId: z.string().optional(),
supportsImmutableAssets: z.boolean().optional(), supportsImmutableAssets: z.boolean().optional(),
outputHashSalt: z.string().optional(), outputHashSalt: z.string().optional(),
......
...@@ -488,6 +488,16 @@ export function resolveCssChunkingMode( ...@@ -488,6 +488,16 @@ export function resolveCssChunkingMode(
return 'loose' return 'loose'
} }
export interface DeprecatedConfig {
/**
* Use the legacy loose App Router matching behavior instead of requiring
* every URL to construct a complete parallel route tree.
*
* @default false
*/
looseRouteMatching?: true
}
export interface ExperimentalConfig { export interface ExperimentalConfig {
/** Nudge coding agents about security upgrades, stable releases, or Future Defaults. */ /** Nudge coding agents about security upgrades, stable releases, or Future Defaults. */
agenticAutoUpgrade?: 'security' | 'latest' | 'future' | false agenticAutoUpgrade?: 'security' | 'latest' | 'future' | false
...@@ -1478,9 +1488,9 @@ export interface ExperimentalConfig { ...@@ -1478,9 +1488,9 @@ export interface ExperimentalConfig {
/** /**
* Omits catch-all-derived App Router matchers that cannot construct a * Omits catch-all-derived App Router matchers that cannot construct a
* complete parallel route tree for their URL. This requires * complete parallel route tree.
* `explicitParallelRouteChildren`; setting that option to `false` also *
* disables strict route matching. * @internal Used by the Next.js internals only.
*/ */
strictRouteMatching?: boolean strictRouteMatching?: boolean
...@@ -2159,6 +2169,12 @@ export interface NextConfig { ...@@ -2159,6 +2169,12 @@ export interface NextConfig {
*/ */
agentRules?: boolean agentRules?: boolean
/**
* Options for deprecated features that are still available for backwards
* compatibility.
*/
deprecated?: DeprecatedConfig
/** /**
* Enable experimental features. Note that all experimental features are subject to breaking changes in the future. * Enable experimental features. Note that all experimental features are subject to breaking changes in the future.
*/ */
...@@ -2338,6 +2354,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2338,6 +2354,7 @@ export const defaultConfig = Object.freeze({
static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH, static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH,
}, },
adapterPath: process.env.NEXT_ADAPTER_PATH || undefined, adapterPath: process.env.NEXT_ADAPTER_PATH || undefined,
deprecated: {} as DeprecatedConfig,
experimental: { experimental: {
agentFeedback: false, agentFeedback: false,
coldCacheBadge: false, coldCacheBadge: false,
...@@ -2432,7 +2449,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2432,7 +2449,7 @@ export const defaultConfig = Object.freeze({
slowModuleDetection: undefined, slowModuleDetection: undefined,
globalNotFound: false, globalNotFound: false,
explicitParallelRouteChildren: true, explicitParallelRouteChildren: true,
strictRouteMatching: false, strictRouteMatching: true,
browserDebugInfoInTerminal: 'warn', browserDebugInfoInTerminal: 'warn',
lockDistDir: true, lockDistDir: true,
disableResumeDataCacheCompression: false, disableResumeDataCacheCompression: false,
......
import { PHASE_INFO, PHASE_PRODUCTION_BUILD } from '../api/constants' import { PHASE_INFO, PHASE_PRODUCTION_BUILD } from '../api/constants'
import {
getStrictRouteMatchingDefaultWarning,
STRICT_ROUTE_MATCHING_DEFAULT_WARNING,
} from './lib/router-utils/strict-route-matching-config'
import { configSchema } from './config-schema'
describe('loadConfig', () => { describe('loadConfig', () => {
let loadConfig: typeof import('./config').default let loadConfig: typeof import('./config').default
...@@ -194,18 +199,41 @@ describe('loadConfig', () => { ...@@ -194,18 +199,41 @@ describe('loadConfig', () => {
}) })
describe('parallel route matching flags', () => { describe('parallel route matching flags', () => {
it('allows explicit children detection without strict route matching', async () => { it('enables strict route matching by default and exposes the opt-out warning', async () => {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {},
})
expect(result.experimental.strictRouteMatching).toBe(true)
expect(getStrictRouteMatchingDefaultWarning(result)).toBe(
STRICT_ROUTE_MATCHING_DEFAULT_WARNING
)
})
it('allows loose route matching through the deprecated opt-out', async () => {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { deprecated: {
explicitParallelRouteChildren: true, looseRouteMatching: true,
strictRouteMatching: false,
}, },
}, },
}) })
expect(result.experimental.explicitParallelRouteChildren).toBe(true)
expect(result.experimental.strictRouteMatching).toBe(false) expect(result.experimental.strictRouteMatching).toBe(false)
expect(getStrictRouteMatchingDefaultWarning(result)).toBeUndefined()
})
it('only accepts true for the deprecated opt-out', () => {
expect(
configSchema.safeParse({
deprecated: { looseRouteMatching: true },
}).success
).toBe(true)
expect(
configSchema.safeParse({
deprecated: { looseRouteMatching: false },
}).success
).toBe(false)
}) })
it('disables strict route matching when explicit children detection is disabled', async () => { it('disables strict route matching when explicit children detection is disabled', async () => {
...@@ -213,13 +241,13 @@ describe('loadConfig', () => { ...@@ -213,13 +241,13 @@ describe('loadConfig', () => {
customConfig: { customConfig: {
experimental: { experimental: {
explicitParallelRouteChildren: false, explicitParallelRouteChildren: false,
strictRouteMatching: true,
}, },
}, },
}) })
expect(result.experimental.explicitParallelRouteChildren).toBe(false) expect(result.experimental.explicitParallelRouteChildren).toBe(false)
expect(result.experimental.strictRouteMatching).toBe(false) expect(result.experimental.strictRouteMatching).toBe(false)
expect(getStrictRouteMatchingDefaultWarning(result)).toBeUndefined()
}) })
}) })
......
...@@ -456,6 +456,9 @@ function assignDefaultsAndValidate( ...@@ -456,6 +456,9 @@ function assignDefaultsAndValidate(
}, },
} }
result.experimental.strictRouteMatching =
!result.deprecated.looseRouteMatching
// Pruning assumes that children only exists when it is backed by an // Pruning assumes that children only exists when it is backed by an
// ordinary route branch. Restoring the legacy implicit children slot must // ordinary route branch. Restoring the legacy implicit children slot must
// therefore also restore the legacy matcher behavior. // therefore also restore the legacy matcher behavior.
......
...@@ -116,6 +116,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi ...@@ -116,6 +116,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi
import { DeferredEmit } from '../../shared/lib/turbopack/deferred-emit' import { DeferredEmit } from '../../shared/lib/turbopack/deferred-emit'
import { getSupportedBrowsers } from '../../build/get-supported-browsers' import { getSupportedBrowsers } from '../../build/get-supported-browsers'
import { printBuildErrors } from '../../build/print-build-errors' import { printBuildErrors } from '../../build/print-build-errors'
import { getStrictRouteMatchingDefaultWarning } from '../lib/router-utils/strict-route-matching-config'
import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs' import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import { seedTurbopackCacheIfNeeded } from '../../lib/turbopack-cache-seed' import { seedTurbopackCacheIfNeeded } from '../../lib/turbopack-cache-seed'
...@@ -1140,7 +1141,10 @@ export async function createHotReloaderTurbopack( ...@@ -1140,7 +1141,10 @@ export async function createHotReloaderTurbopack(
// Certain crtical issues prevent any entrypoints from being constructed so return early // Certain crtical issues prevent any entrypoints from being constructed so return early
if (!('routes' in entrypoints.value)) { if (!('routes' in entrypoints.value)) {
printBuildErrors(entrypoints, true) printBuildErrors(entrypoints, true, {
strictRouteMatchingDefaultWarning:
getStrictRouteMatchingDefaultWarning(nextConfig),
})
currentEntriesHandlingResolve!() currentEntriesHandlingResolve!()
currentEntriesHandlingResolve = undefined currentEntriesHandlingResolve = undefined
......
...@@ -102,6 +102,7 @@ import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app ...@@ -102,6 +102,7 @@ import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app
import { MissingCanonicalInterceptionRoutesError } from '../../../shared/lib/errors/missing-canonical-interception-routes-error' import { MissingCanonicalInterceptionRoutesError } from '../../../shared/lib/errors/missing-canonical-interception-routes-error'
import { IncompatibleParallelRouteSlotsError } from '../../../shared/lib/errors/incompatible-parallel-route-slots-error' import { IncompatibleParallelRouteSlotsError } from '../../../shared/lib/errors/incompatible-parallel-route-slots-error'
import { findMissingCanonicalInterceptionRoutes } from '../../../shared/lib/router/utils/interception-routes' import { findMissingCanonicalInterceptionRoutes } from '../../../shared/lib/router/utils/interception-routes'
import { getStrictRouteMatchingDefaultWarning } from './strict-route-matching-config'
import { import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
...@@ -1147,6 +1148,10 @@ async function startWatcher( ...@@ -1147,6 +1148,10 @@ async function startWatcher(
for (const error of routeMatchingErrors) { for (const error of routeMatchingErrors) {
Log.error(error.message) Log.error(error.message)
} }
const warning = getStrictRouteMatchingDefaultWarning(nextConfig)
if (warning) {
Log.warnOnce(warning)
}
} }
// Turbopack reports route-matching failures as app-structure issues. // Turbopack reports route-matching failures as app-structure issues.
// Webpack needs an HMR server error so dev can finish booting and surface // Webpack needs an HMR server error so dev can finish booting and surface
......
import type { NextConfigComplete } from '../../config-shared'
export const STRICT_ROUTE_MATCHING_DEFAULT_WARNING =
"Strict route matching is enabled by default. This validation indicates a bug in your app's route structure, but you can temporarily restore loose route matching by setting `deprecated.looseRouteMatching` to `true` in your Next.js config."
export function getStrictRouteMatchingDefaultWarning(
config: NextConfigComplete
): string | undefined {
return config.experimental.strictRouteMatching
? STRICT_ROUTE_MATCHING_DEFAULT_WARNING
: undefined
}
...@@ -42,6 +42,8 @@ describe('canonical-interception-routes', () => { ...@@ -42,6 +42,8 @@ describe('canonical-interception-routes', () => {
} }
`) `)
} }
expectDefaultStrictRouteMatchingWarning(next.cliOutput)
} else { } else {
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
...@@ -53,10 +55,17 @@ describe('canonical-interception-routes', () => { ...@@ -53,10 +55,17 @@ describe('canonical-interception-routes', () => {
Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed." Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed."
`) `)
expectDefaultStrictRouteMatchingWarning(cliOutput)
} }
}) })
}) })
function expectDefaultStrictRouteMatchingWarning(output: string): void {
expect(stripAnsi(output)).toContain(
'you can temporarily restore loose route matching by setting `deprecated.looseRouteMatching` to `true`'
)
}
function extractMissingCanonicalRoutesError(output: string): string { function extractMissingCanonicalRoutesError(output: string): string {
const normalizedOutput = stripAnsi(output) const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf( const start = normalizedOutput.indexOf(
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
...@@ -53,6 +53,7 @@ describe('incompatible-parallel-route-slots', () => { ...@@ -53,6 +53,7 @@ describe('incompatible-parallel-route-slots', () => {
expect(`${stripAnsi(next.cliOutput)}\n${response}`).not.toContain( expect(`${stripAnsi(next.cliOutput)}\n${response}`).not.toContain(
'strict route matching retained the incomplete route matcher' 'strict route matching retained the incomplete route matcher'
) )
expectDefaultStrictRouteMatchingWarning(next.cliOutput)
} else { } else {
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
...@@ -71,10 +72,17 @@ describe('incompatible-parallel-route-slots', () => { ...@@ -71,10 +72,17 @@ describe('incompatible-parallel-route-slots', () => {
expect(stripAnsi(cliOutput)).not.toContain( expect(stripAnsi(cliOutput)).not.toContain(
'strict route matching retained the incomplete route matcher' 'strict route matching retained the incomplete route matcher'
) )
expectDefaultStrictRouteMatchingWarning(cliOutput)
} }
}) })
}) })
function expectDefaultStrictRouteMatchingWarning(output: string): void {
expect(stripAnsi(output)).toContain(
'you can temporarily restore loose route matching by setting `deprecated.looseRouteMatching` to `true`'
)
}
function extractIncompatibleSlotsError(output: string): string { function extractIncompatibleSlotsError(output: string): string {
const normalizedOutput = stripAnsi(output) const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf( const start = normalizedOutput.indexOf(
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
...@@ -7,10 +7,6 @@ const nextConfig = { ...@@ -7,10 +7,6 @@ const nextConfig = {
// intercepted layouts omit children, while a real children branch still // intercepted layouts omit children, while a real children branch still
// uses the marker needed to preserve its active state during navigation. // uses the marker needed to preserve its active state during navigation.
explicitParallelRouteChildren: true, explicitParallelRouteChildren: true,
// Interception catch-alls retain every sibling owned by the host layout.
// Strict matching must not mistake those retained slots for incomplete
// route coverage and prune the interception matcher.
strictRouteMatching: true,
}, },
} }
......
// `/parallel-scroll/nav` only has a page in @modal. Declare what a direct
// request should render for children instead of relying on the legacy
// synthesized not-found fallback that soft navigation happened to hide.
export default function Default() {
return null
}
...@@ -2,6 +2,11 @@ ...@@ -2,6 +2,11 @@
This fixture contains scenarios that **SHOULD throw `MissingDefaultParallelRouteError`** during build. This fixture contains scenarios that **SHOULD throw `MissingDefaultParallelRouteError`** during build.
It opts out of strict route matching because strict matching removes these
incomplete routes before the legacy loader-tree validation can run. Once strict
matching is the only mode, this fixture should be removed in favor of the
equivalent strict diagnostic.
## Why These Should Error ## Why These Should Error
All scenarios in this fixture have: All scenarios in this fixture have:
......
/** @type {import('next').NextConfig} */
const nextConfig = {
deprecated: {
// This fixture intentionally exercises the legacy loader-tree validation
// for incomplete parallel routes. Strict matching removes those routes
// before that validation can run. Once strict matching is the only mode,
// this fixture should be removed in favor of the strict diagnostic.
looseRouteMatching: true,
},
}
module.exports = nextConfig
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { deprecated: {
// This fixture exercises the legacy missing-default validation directly. // This fixture exercises the legacy missing-default validation directly.
// Keep that coverage if strict route matching becomes the default; once // Keep that coverage if strict route matching becomes the default; once
// strict matching is the only mode, this fixture can be removed. // strict matching is the only mode, this fixture can be removed.
strictRouteMatching: false, looseRouteMatching: true,
}, },
} }
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
// The drawer and modal URLs only match their respective named slots. This
// explicit fallback makes those URLs complete on a direct request while soft
// navigation can continue to preserve the active children page.
export default function Default() {
return null
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
...@@ -47,6 +47,8 @@ describe('unmatched-app-pages', () => { ...@@ -47,6 +47,8 @@ describe('unmatched-app-pages', () => {
} }
`) `)
} }
expectDefaultStrictRouteMatchingWarning(next.cliOutput)
} else { } else {
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
...@@ -64,10 +66,17 @@ describe('unmatched-app-pages', () => { ...@@ -64,10 +66,17 @@ describe('unmatched-app-pages', () => {
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages." Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages."
`) `)
expectDefaultStrictRouteMatchingWarning(cliOutput)
} }
}) })
}) })
function expectDefaultStrictRouteMatchingWarning(output: string): void {
expect(stripAnsi(output)).toContain(
'you can temporarily restore loose route matching by setting `deprecated.looseRouteMatching` to `true`'
)
}
function extractUnmatchedPagesError(output: string): string { function extractUnmatchedPagesError(output: string): string {
const normalizedOutput = stripAnsi(output) const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf( const start = normalizedOutput.indexOf(
......
import { notFound } from 'next/navigation'
// The layout intentionally does not render children for /nested/foo or
// /nested/bar. An explicit not-found default keeps that choice valid under
// strict matching without changing the rendered named slots.
export default function Default() {
notFound()
}
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