Unverified Commit f81c34f8 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Hard-navigate to app routes shadowed by a pages dynamic route (#95185)

When an App Router route begins with a dynamic segment (for example
`app/[locale]/about`), a client-side navigation from a Pages Router page
could render the wrong route. The Pages Router resolves the destination
against its own routes only, so `/en/about` would match a less specific
Pages Router dynamic route such as `pages/[locale]/[category]` instead
of the App Router page. The server pools app and pages routes and ranks
them by specificity, so a hard reload always rendered the correct App
Router page; only the client-side soft navigation diverged.

The client router filter is responsible for detecting destinations owned
by the other router and forcing a hard navigation, but
`createClientRouterFilter` only recorded the static prefix of a dynamic
route. App routes whose first segment is dynamic have no static prefix,
so they contributed nothing to the filter and the Pages Router never
learned to hand them off. The filter now also stores a normalized
pattern for those routes, with dynamic segments replaced by a
placeholder token (`/[locale]/about` becomes `/[]/about`). After the
Pages Router resolves a navigation to a dynamic route,
`hasDynamicFilterCandidate` reconstructs the candidate app-route
patterns from that route and the concrete path and triggers a hard
navigation when any candidate is present in the dynamic filter. This
also covers catch-all and optional catch-all pages routes, whose final
parameter absorbs a variable number of segments. The shared placeholder
token and the client-side check live in the new
`dynamic-filter-pattern.ts`, while the build-only encoder stays in
`create-client-router-filter.ts`.

The change only ever turns a soft navigation into a hard navigation, and
only when an app route is genuinely more specific than the resolved
pages route, so a structural match always agrees with the server's
resolution. Apps without dynamic app routes are unaffected because the
dynamic filter stays empty.

The `pages-to-app-routing` end-to-end suite is restructured around a
`fixtures/` directory and gains coverage for the dynamic-segment
shadowing, the catch-all and optional catch-all variants, `basePath`,
middleware, and a guard that legitimate Pages Router dynamic routes
still navigate client-side. The first request to a not-yet-compiled
dynamic route can return a transient 404 in development, a pre-existing
source of CI flakiness, so the tests now warm the route up with a direct
request before driving the browser.

fixes #74696
parent ff3a5f9d
......@@ -8,6 +8,7 @@ import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../shared/lib/router/utils/interception-routes'
import { DYNAMIC_FILTER_PLACEHOLDER } from '../shared/lib/router/utils/dynamic-filter-pattern'
export function createClientRouterFilter(
paths: string[],
......@@ -42,6 +43,13 @@ export function createClientRouterFilter(
if (subPath) {
dynamicPaths.add(subPath)
} else {
// The route begins with a dynamic segment, so it has no static
// prefix to anchor the prefix-based dynamic filter on (e.g.
// `/[locale]/about`). Store its normalized pattern instead so the
// client can still detect it when a pages dynamic route would
// otherwise shadow it.
dynamicPaths.add(normalizeRouteToFilterPattern(path))
}
} else {
staticPaths.add(path)
......@@ -72,3 +80,18 @@ export function createClientRouterFilter(
}
return data
}
/**
* Replace every dynamic segment of a route with the placeholder token, e.g.
* `/[locale]/about` -> `/[]/about`, `/[lang]` -> `/[]`. This is the encode half
* of the dynamic filter; the pages router decodes it with
* `hasDynamicFilterCandidate`, and both rely on `DYNAMIC_FILTER_PLACEHOLDER`.
*/
function normalizeRouteToFilterPattern(route: string): string {
return route
.split('/')
.map((segment) =>
segment.startsWith('[') ? DYNAMIC_FILTER_PLACEHOLDER : segment
)
.join('/')
}
......@@ -23,6 +23,7 @@ import { isDynamicRoute } from './utils/is-dynamic'
import { parseRelativeUrl } from './utils/parse-relative-url'
import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex'
import { hasDynamicFilterCandidate } from './utils/dynamic-filter-pattern'
import { formatWithValidation } from './utils/format-url'
import { detectDomainLocale } from '../../../client/detect-domain-locale'
import { parsePath } from './utils/parse-path'
......@@ -1518,6 +1519,36 @@ export default class Router implements BaseRouter {
}
}
// The pages client router resolves a navigation against pages routes only.
// When it resolves to a dynamic pages route, an app route that begins with
// a dynamic segment may be more specific and own this path on the server
// (e.g. `/en/about` resolves to the pages route `/[locale]/[category]`, but
// the app route `/[locale]/about` should win). Such app routes have no
// static prefix for the early `_bfl` check, so reconstruct the candidate
// patterns from the resolved route and hard navigate when one is in the
// dynamic filter.
if (
!isQueryUpdating &&
!options.shallow &&
process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED &&
this._bfl_d &&
isDynamicRoute(pathname)
) {
const concretePathname = removeTrailingSlash(
parseRelativeUrl(cleanedAs).pathname
)
const isShadowedByAppRoute = hasDynamicFilterCandidate(
pathname,
concretePathname,
(candidate) => !!this._bfl_d?.contains(candidate)
)
if (isShadowedByAppRoute) {
handleHardNavigation({ url: as, router: this })
return new Promise(() => {})
}
}
if (!isLocalURL(as)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
......
// The client router filter handles app routes that begin with a dynamic segment
// (e.g. `/[locale]/about`). Such routes have no static prefix to anchor the
// prefix-based dynamic filter on, so the build-time producer
// (`createClientRouterFilter`) stores them as a normalized pattern with dynamic
// segments replaced by the placeholder token below, and the pages router
// reconstructs matching candidates from the route it resolved a navigation to.
/**
* A token that can never collide with a real path segment (dynamic segments are
* always `[name]`, `[...name]`, or `[[...name]]`, and static segments never
* equal `[]`). Shared with the builder's `normalizeRouteToFilterPattern`.
*/
export const DYNAMIC_FILTER_PLACEHOLDER = '[]'
/**
* Beyond this many dynamic segments the 2^n candidate set is skipped. Real
* routes never approach this; the cap only guards against pathological input.
*/
const MAX_DYNAMIC_SEGMENTS = 8
/**
* Test whether any app route that could shadow the resolved pages route passes
* `test` (typically a dynamic-filter membership check). An app route can only
* win over a matching pages route by turning some of that route's dynamic
* positions into static segments, so we enumerate keeping each such position
* either literal (static in the app route) or a placeholder (still dynamic in
* the app route) and return as soon as one passes.
*
* A static route segment pins its position to that literal; every other
* concrete position is dynamic and thus a candidate for a placeholder. That
* includes the tail a trailing catch-all (`[...slug]`/`[[...slug]]`) absorbs,
* which is why a catch-all route legitimately has fewer segments than the path
* it matched.
*
* Order is irrelevant: any match means the path is shadowed, and resolution is
* handed to the server via a hard navigation regardless of which candidate
* matched.
*/
export function hasDynamicFilterCandidate(
routePattern: string,
concretePathname: string,
test: (candidate: string) => boolean
): boolean {
const routeSegments = routePattern.split('/')
const concreteSegments = concretePathname.split('/')
const lastSegment = routeSegments[routeSegments.length - 1] ?? ''
const hasCatchAll =
lastSegment.startsWith('[...') || lastSegment.startsWith('[[...')
// A non-catch-all route always has the same segment count as the path it
// matched; a mismatch there means the inputs don't line up. A catch-all route
// legitimately differs because its final param absorbs the remaining
// segments.
if (!hasCatchAll && routeSegments.length !== concreteSegments.length) {
return false
}
// Collect the concrete positions that are dynamic in the matched route: any
// position without a static route segment (a dynamic param, or one absorbed
// by the trailing catch-all).
const dynamicIndices: number[] = []
for (let i = 1; i < concreteSegments.length; i++) {
// An empty concrete segment is not a real path segment (splitting `/`
// yields a trailing `''`). A trailing optional catch-all matches it by
// absorbing nothing, so it must not be treated as a dynamic position:
// otherwise `/` would reconstruct the `/[]` candidate and spuriously match
// a root-level dynamic app route such as `/[lang]`, which does not own `/`.
if (concreteSegments[i] === '') {
continue
}
const routeSegment = routeSegments[i]
const isStaticSegment =
routeSegment !== undefined && !routeSegment.startsWith('[')
if (!isStaticSegment) {
dynamicIndices.push(i)
}
}
if (
dynamicIndices.length === 0 ||
dynamicIndices.length > MAX_DYNAMIC_SEGMENTS
) {
return false
}
// Enumerate the keep-literal/placeholder combinations as a bitmask over those
// positions (a set bit keeps the concrete value, an unset bit is a
// placeholder). The all-literal combination is skipped: a fully concrete path
// is a static route, already covered by the static filter and the early
// prefix check, so it can never appear in the dynamic filter as a pattern.
const allLiteral = (1 << dynamicIndices.length) - 1
for (let mask = 0; mask < allLiteral; mask++) {
const segments = concreteSegments.slice()
for (let bit = 0; bit < dynamicIndices.length; bit++) {
if ((mask & (1 << bit)) === 0) {
segments[dynamicIndices[bit]] = DYNAMIC_FILTER_PLACEHOLDER
}
}
if (test(segments.join('/'))) {
return true
}
}
return false
}
type Props = {
params: Promise<{ locale: string }>
}
export default async function About({ params }: Props) {
const { locale } = await params
return <h1 id="page-title">App About: {locale}</h1>
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
basePath: '/base',
}
module.exports = nextConfig
import type { GetServerSidePropsContext } from 'next'
type Props = {
category: string
locale: string
}
export default function Category({ category, locale }: Props) {
return (
<h1 id="page-title">
Pages Category: {String(category)} ({locale})
</h1>
)
}
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
return {
props: {
category: params?.category,
locale: params?.locale,
},
}
}
import type { GetServerSidePropsContext } from 'next'
import Link from 'next/link'
type Props = {
locale: string
}
export default function SomePage({ locale }: Props) {
return (
<>
<h1 id="page-title">Pages Some Page: {locale}</h1>
<Link id="to-locale-about-link" href={`/${locale}/about`}>
To App About
</Link>
</>
)
}
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
return {
props: {
locale: params?.locale,
},
}
}
type Props = {
params: Promise<{ lang: string }>
}
export default async function About({ params }: Props) {
const { lang } = await params
return <h1 id="page-title">App About: {lang}</h1>
}
type Props = {
params: Promise<{ lang: string }>
}
export default async function Lang({ params }: Props) {
const { lang } = await params
return <h1 id="page-title">App Lang: {lang}</h1>
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
import type { GetServerSidePropsContext } from 'next'
type Props = {
slug: string[]
}
export default function Catchall({ slug }: Props) {
return <h1 id="page-title">Pages Catchall: {slug.join('/')}</h1>
}
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
return {
props: {
slug: (params?.slug as string[]) ?? [],
},
}
}
import Link from 'next/link'
export default function Home() {
return (
<>
<h1 id="page-title">Pages Home</h1>
<Link id="to-lang-link" href="/en">
To App Lang
</Link>
<Link id="to-lang-about-link" href="/en/about">
To App About
</Link>
</>
)
}
type Props = {
params: Promise<{ lang: string }>
}
export default async function About({ params }: Props) {
const { lang } = await params
return <h1 id="page-title">App About: {lang}</h1>
}
type Props = {
params: Promise<{ lang: string }>
}
export default async function Lang({ params }: Props) {
const { lang } = await params
return <h1 id="page-title">App Lang: {lang}</h1>
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import type { GetServerSidePropsContext } from 'next'
import Link from 'next/link'
type Props = {
slug: string[]
}
export default function OptionalCatchall({ slug }: Props) {
// The optional catch-all also owns `/`, so it doubles as the start page.
if (slug.length === 0) {
return (
<>
<h1 id="page-title">Pages Home</h1>
<Link id="to-lang-link" href="/en">
To App Lang
</Link>
<Link id="to-lang-about-link" href="/en/about">
To App About
</Link>
</>
)
}
return (
<>
<h1 id="page-title">Pages Optional Catchall: {slug.join('/')}</h1>
<Link id="to-home-link" href="/">
To Home
</Link>
</>
)
}
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
return {
props: {
slug: (params?.slug as string[]) ?? [],
},
}
}
type Props = {
params: Promise<{ locale: string }>
}
export default async function About({ params }: Props) {
const { locale } = await params
return <h1 id="page-title">App About: {locale}</h1>
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
import type { NextRequest } from 'next/server'
// Present (matching all routes) so the shadowing checks are exercised on the
// pages-router navigation path that runs middleware, as a real i18n app would.
export function middleware(_request: NextRequest) {}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import type { GetServerSidePropsContext } from 'next'
type Props = {
category: string
locale: string
}
export default function Category({ category, locale }: Props) {
return (
<h1 id="page-title">
Pages Category: {String(category)} ({locale})
</h1>
)
}
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
return {
props: {
category: params?.category,
locale: params?.locale,
},
}
}
import type { GetStaticPropsContext } from 'next'
import Link from 'next/link'
type Props = {
locale: string
}
export default function SomePage({ locale }: Props) {
return (
<>
<h1 id="page-title">Pages Some Page: {locale}</h1>
<Link id="to-locale-about-link" href={`/${locale}/about`}>
To App About
</Link>
<Link id="to-category-link" href={`/${locale}/products`}>
To Pages Category
</Link>
</>
)
}
export async function getStaticProps({ params }: GetStaticPropsContext) {
return {
props: {
locale: params?.locale,
},
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { locale: 'en' } }],
fallback: false,
}
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { nextTestSetup, type NextInstance } from 'e2e-utils'
import { retry } from 'next-test-utils'
// In dev the first request to a not-yet-registered dynamic route can return a
// transient 404 (a cold-start race, observed flaking in CI). Warm the route up
// with a direct request before driving the browser so the navigation is
// deterministic.
async function warmUpRoute(next: NextInstance, pathname: string) {
await retry(async () => {
const res = await next.fetch(pathname)
expect(res.status).toBe(200)
})
}
describe('pages-to-app-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
files: join(__dirname, 'fixtures', 'default'),
})
it('should work using browser', async () => {
it('should client-navigate from a pages route to an app route', async () => {
await warmUpRoute(next, '/abc')
const browser = await next.browser('/abc')
expect(await browser.elementByCss('#params').text()).toBe(
'Params: {"slug":"abc"}'
......@@ -19,3 +34,234 @@ describe('pages-to-app-routing', () => {
expect(await browser.elementByCss('#app-page').text()).toBe('About')
})
})
// Regression test for https://github.com/vercel/next.js/issues/74696.
//
// Route structure:
//
// ```
// app/[locale]/about/page.tsx -> App Router
// pages/[locale]/some-page/index.tsx -> Pages Router (start page)
// pages/[locale]/[category]/index.tsx -> Pages Router (matches /en/about)
// ```
//
// `/en/about` is served by the App Router page `app/[locale]/about` even though
// the Pages Router dynamic route `pages/[locale]/[category]` also matches it:
// the more specific static `about` segment wins, the same way `/en/some-page`
// is served by `some-page` rather than `[category]`. A hard reload of
// `/en/about` renders the App Router page. A client-side navigation to it from
// a Pages Router page must reach that same App Router page, not the Pages
// Router `[category]` route.
//
// All three pages expose a `#page-title` element with distinct text, so the
// rendered route is asserted directly on that text.
describe('pages-to-app-routing with cross-router shadowing', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'cross-router-shadowing'),
})
it('should client-navigate to the app route, not the shadowing pages dynamic route', async () => {
await warmUpRoute(next, '/en/some-page')
const browser = await next.browser('/en/some-page')
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Some Page: en'
)
await browser.elementByCss('#to-locale-about-link').click()
// Wait until the navigation has committed (the URL reflects the target and
// the title is no longer the start page). In dev the conflicting route is
// compiled on demand, so this can take a few seconds.
await retry(async () => {
expect(await browser.url()).toContain('/en/about')
expect(await browser.elementByCss('#page-title').text()).not.toBe(
'Pages Some Page: en'
)
}, 15000)
expect(await browser.elementByCss('#page-title').text()).toBe(
'App About: en'
)
})
it('should render the app route on a hard reload of the same URL', async () => {
const browser = await next.browser('/en/about')
expect(await browser.elementByCss('#page-title').text()).toBe(
'App About: en'
)
})
it('should still client-navigate to a real pages dynamic route (no spurious hard navigation)', async () => {
const browser = await next.browser('/en/some-page')
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Some Page: en'
)
await browser.elementByCss('#to-category-link').click()
await retry(async () => {
expect(await browser.url()).toContain('/en/products')
expect(await browser.elementByCss('#page-title').text()).not.toBe(
'Pages Some Page: en'
)
}, 15000)
// `/en/products` is owned by the Pages Router `[category]` route, not an
// app route, so this navigation must stay a client-side navigation within
// the Pages Router rather than hard-navigate.
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Category: products (en)'
)
})
})
// The shadowing pages route can also be a catch-all. `/en` and `/en/about` are
// App Router pages (`app/[lang]` and `app/[lang]/about`), but a Pages Router
// catch-all matches them too. A catch-all absorbs a variable number of
// segments, so these variants exercise both a single-segment (`/en`) and a
// multi-segment (`/en/about`) target. The optional catch-all (`[[...slug]]`)
// additionally owns `/`.
const catchAllVariants = [
{ label: 'catch-all', dir: 'cross-router-shadowing-catch-all' },
{
label: 'optional catch-all',
dir: 'cross-router-shadowing-optional-catch-all',
},
]
for (const variant of catchAllVariants) {
describe(`pages-to-app-routing with cross-router shadowing via a ${variant.label}`, () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', variant.dir),
})
it('should client-navigate to a single-segment app route shadowed by the pages catch-all', async () => {
await warmUpRoute(next, '/')
const browser = await next.browser('/')
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Home'
)
await browser.elementByCss('#to-lang-link').click()
await retry(async () => {
expect(await browser.url()).toContain('/en')
expect(await browser.elementByCss('#page-title').text()).not.toBe(
'Pages Home'
)
}, 15000)
expect(await browser.elementByCss('#page-title').text()).toBe(
'App Lang: en'
)
})
it('should client-navigate to a multi-segment app route shadowed by the pages catch-all', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Home'
)
await browser.elementByCss('#to-lang-about-link').click()
await retry(async () => {
expect(await browser.url()).toContain('/en/about')
expect(await browser.elementByCss('#page-title').text()).not.toBe(
'Pages Home'
)
}, 15000)
expect(await browser.elementByCss('#page-title').text()).toBe(
'App About: en'
)
})
})
}
// The same cross-router navigation must still reach the App Router page when
// the app is served under a `basePath`.
describe('pages-to-app-routing with cross-router shadowing under basePath', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'cross-router-shadowing-basepath'),
})
it('should client-navigate to the app route, not the shadowing pages dynamic route', async () => {
await warmUpRoute(next, '/base/en/some-page')
const browser = await next.browser('/base/en/some-page')
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Some Page: en'
)
await browser.elementByCss('#to-locale-about-link').click()
await retry(async () => {
expect(await browser.url()).toContain('/base/en/about')
expect(await browser.elementByCss('#page-title').text()).not.toBe(
'Pages Some Page: en'
)
}, 15000)
expect(await browser.elementByCss('#page-title').text()).toBe(
'App About: en'
)
})
})
// A pages optional catch-all (`[[...slug]]`) owns `/` by absorbing zero
// segments, but a root-level dynamic app route (`app/[lang]`) does not own `/`
// (it requires one segment). Navigating to `/` from a Pages Router page must
// therefore stay a client-side navigation and must not hard-navigate to the App
// Router. The page renders correctly either way (the server owns `/`), so the
// hard navigation is detected from the document request rather than the
// rendered text.
describe('pages-to-app-routing with a pages optional catch-all owning the root', () => {
const { next, isNextDev } = nextTestSetup({
files: join(
__dirname,
'fixtures',
'cross-router-shadowing-optional-catch-all'
),
})
// Production only: in dev, navigating to the optional catch-all index `/`
// always hard-navigates because its data response 404s and the Pages Router
// falls back to a full reload, which would mask what this test verifies. That
// dev-only 404 is a separate pre-existing issue.
const skipInDev = isNextDev ? it.skip : it
skipInDev(
'should client-navigate to the root without a hard navigation',
async () => {
// A two-segment path no app route matches, so it is owned by the pages
// optional catch-all (a one-segment path like `/start` would be the app
// `/[lang]` route instead).
const browser = await next.browser('/start/here')
// eslint-disable-next-line jest/no-standalone-expect
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Optional Catchall: start/here'
)
let didHardNavigateToRoot = false
browser.on('request', (req) => {
if (req.isNavigationRequest() && new URL(req.url()).pathname === '/') {
didHardNavigateToRoot = true
}
})
await browser.elementByCss('#to-home-link').click()
await retry(async () => {
expect(await browser.elementByCss('#page-title').text()).toBe(
'Pages Home'
)
}, 15000)
// eslint-disable-next-line jest/no-standalone-expect
expect(didHardNavigateToRoot).toBe(false)
}
)
})
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