Unverified Commit 5979942c authored by Benjamin Staneck's avatar Benjamin Staneck Committed by GitHub

Pages Router: key the client router filter prefetch marker by the `as` path (#98182)

### What?

`Router.prefetch()` in the Pages Router evaluates the client router
filter (`_bfl`) against the `as` path, but stored the resulting `{
__appRouter: true }` marker in `router.components` under the `href`
pathname. `Router.change()` looked the marker up with the `href`
pathname as well. This PR keys the marker by the normalized `as`
pathname and effective locale, preserves existing cache entries, and
checks for markers before and after route resolution.

### Why?

`href` and `as` are the same URL for most links, so the mismatch was
invisible. They differ for the "route as modal" pattern
(`examples/with-route-as-modal`): `href` stays on the current route
(`router.pathname` + query) and `as` shows the pretty URL. When the
filter matches `as`, including a false positive, the marker could
replace the cached route info of the page the user is currently on:

- On a static route (`/`), the `change()` guard fired for later shallow
navigation and hard-navigated.
- On a dynamic route, the marker was stored under the pattern
(`/players/[name]`) but looked up with the concrete path
(`/players/alice`). The guard could miss it, and shallow navigation
could render without page props, causing missing content or an
application error.

A prefetch must also preserve already-loaded route info when its key
matches the current route. This can happen when the page was reached
through a rewrite and its canonical URL is prefetched. Hash-only
navigation renders that cached entry directly, so preserving it lets the
normal client-side hash update retain the page props and update
`router.asPath`.

Fixes #98180

### How?

- `getAppRouterMarkerKey(router, as, locale)` parses the pathname,
normalizes the trailing slash, and preserves the effective locale. It
expects a path without `basePath` and does not strip that prefix again.
An explicit locale prefix takes precedence over the supplied locale.
- The helper returns `null` for non-local URLs, leaving their existing
navigation handling unchanged.
- `prefetch()` stores the marker under that key only when the
corresponding cache entry is absent. It does not replace loaded route
info.
- `change()` checks both the normalized `as` key and the `href` route.
It checks the resolved route again after config rewrites, before
`getRouteInfo()` reads the cache.
- Non-shallow navigations continue to consult the client router filter
directly. Hash-only navigation retains its normal client-side path.

The complementary change in #98650 (adopts #98187) adds defensive checks
when `getRouteInfo()` reads marker entries.

### Tests

The e2e suites run in production (`next start`) and deploy modes.
`router.prefetch()` is a no-op in development.

`test/e2e/app-dir/pages-prefetch-as-app-route` covers:

- Hard navigation to an App Router destination after prefetching a link
whose `href` and `as` differ.
- Shallow navigation on static and dynamic Pages Router routes without a
reload or lost server-provided props.
- Hard navigation when the `href` route holds a marker and `as` differs,
or a config rewrite resolves to a marked route.
- Client-side hash navigation after an awaited prefetch of the current
route's canonical URL, with preserved props and an updated
`router.asPath`.

`test/e2e/app-dir/pages-prefetch-as-app-route-base-path` covers an
internal `/docs` route with `basePath: '/docs'`, including navigation to
`/docs/docs` and an unaffected shallow update on the index page.

`test/e2e/app-dir/pages-prefetch-as-app-route-i18n` covers a French-only
redirect prefetch without forcing an unrelated English navigation to
reload. Marker-dependent tests wait for the specific key they need,
rather than any marker.

The fix was also verified at runtime against the reproduction in
https://github.com/Stanzilla/next-pages-router-prefetch-bloom-filter-repro
by patching the compiled `router.js` and re-running the scenario. The
e2e suite was not run locally.

Disclosure: this change and its description were prepared with AI
assistance (Claude Code) on behalf of the author.
parent 05c20cd1
......@@ -152,6 +152,55 @@ function prepareUrlAs(router: NextRouter, url: Url, as?: Url) {
}
}
/**
* Key under which `prefetch()` stores the `{ __appRouter: true }` marker in
* `router.components` and under which `change()` looks it up again.
*
* The client router filter (`_bfl`) is evaluated against the `as` path, so the
* marker has to be keyed by the `as` path as well. Keying it by the `href`
* pathname is only equivalent while `href` and `as` are the same URL. When
* they differ (for example the "route as modal" pattern where `href` stays on
* the current page and `as` shows a pretty URL) a filter match on `as` would
* otherwise mark the pages route behind `href` as an App Router path and
* break every later navigation to that route.
*
* `as` is expected without the `basePath`, which is what both call sites
* hold: `prefetch()` receives it that way from `next/link` and `change()`
* strips it before computing `cleanedAs`. Stripping it again here would turn
* a route that merely starts with the `basePath` (for example the app route
* `/docs` with `basePath: '/docs'`) into `/` and poison the index page.
*
* The key also carries the effective locale, mirroring how `_bfl` evaluates
* `addLocale(as, locale)` against the filter. A match for a French-only
* redirect at `/fr/legacy` must not mark the English `/legacy` page.
*
* Returns `null` when `as` is not a local URL (for example `mailto:` or a
* different origin). Such an `as` can never be an App Router path, and
* `change()` reports it as an invalid `href`/`as` pair further down.
*/
function getAppRouterMarkerKey(
router: Router,
as: string,
locale: string | false | undefined
): string | null {
if (!isLocalURL(as)) {
return null
}
let { pathname } = parseRelativeUrl(as)
let effectiveLocale = locale || router.locale
if (process.env.__NEXT_I18N_SUPPORT) {
const localePathResult = normalizeLocalePath(pathname, router.locales)
pathname = localePathResult.pathname
effectiveLocale = localePathResult.detectedLocale || effectiveLocale
}
return removeTrailingSlash(
addLocale(removeTrailingSlash(pathname), effectiveLocale)
)
}
function resolveDynamicRoute(pathname: string, pages: string[]) {
const cleanPathname = removeTrailingSlash(denormalizePagePath(pathname))
if (cleanPathname === '/404' || cleanPathname === '/_error') {
......@@ -1378,7 +1427,6 @@ export default class Router implements BaseRouter {
// If the url change is only related to a hash change
// We should not proceed. We should only change the state.
if (!isQueryUpdating && this.onlyAHashChange(cleanedAs) && !localeChange) {
nextState.asPath = cleanedAs
Router.events.emit('hashChangeStart', as, routeProps)
......@@ -1446,9 +1494,21 @@ export default class Router implements BaseRouter {
let route = removeTrailingSlash(pathname)
const parsedAsPathname = as.startsWith('/') && parseRelativeUrl(as).pathname
// if we detected the path as app route during prefetching
// trigger hard navigation
if ((this.components[pathname] as any)?.__appRouter) {
// if we detected the `as` path as app route during prefetching
// trigger hard navigation. The marker is keyed by the `as` path, but a
// marker can also sit under the href route when both paths share a
// pages route (`pages/modal.js` next to `app/modal/[id]/page.js`).
// Check both so `getRouteInfo()` never reads a marker as component data.
const appRouterMarkerKey = getAppRouterMarkerKey(
this,
cleanedAs,
nextState.locale
)
if (
(appRouterMarkerKey !== null &&
(this.components[appRouterMarkerKey] as any)?.__appRouter) ||
(this.components[route] as any)?.__appRouter
) {
handleHardNavigation({ url: as, router: this })
return new Promise(() => {})
}
......@@ -1563,6 +1623,15 @@ export default class Router implements BaseRouter {
resolvedAs = removeLocale(removeBasePath(resolvedAs), nextState.locale)
route = removeTrailingSlash(pathname)
// A config rewrite can resolve `href` to another pages route after the
// marker guard above ran. That route can hold a marker from an earlier
// prefetch, so check it again before `getRouteInfo()` reads the cache.
if ((this.components[route] as any)?.__appRouter) {
handleHardNavigation({ url: as, router: this })
return new Promise(() => {})
}
let routeMatch: Params | false = false
if (isDynamicRoute(route)) {
......@@ -2416,7 +2485,6 @@ export default class Router implements BaseRouter {
return
}
let parsed = parseRelativeUrl(url)
const urlPathname = parsed.pathname
let { pathname, query } = parsed
const originalPathname = pathname
......@@ -2554,7 +2622,26 @@ export default class Router implements BaseRouter {
const route = removeTrailingSlash(pathname)
if (await this._bfl(asPath, resolvedAs, options.locale, true)) {
this.components[urlPathname] = { __appRouter: true } as any
const appRouterMarkerKey = getAppRouterMarkerKey(
this,
asPath,
options.locale
)
// A loaded pages route in the cache is ground truth: the page behind
// this key exists and was rendered. This is the case when the current
// page was reached through a rewrite and the canonical URL is
// prefetched, or when a prefetch is still in flight while a navigation
// stores the same route. Replacing that entry with the marker would
// break hash-only changes and shallow navigations, which render the
// cached entry of the current route directly. Non-shallow navigations
// consult the client router filter themselves, so they do not depend
// on the marker to hard navigate.
if (
appRouterMarkerKey !== null &&
this.components[appRouterMarkerKey] === undefined
) {
this.components[appRouterMarkerKey] = { __appRouter: true } as any
}
}
await Promise.all([
......
export default function Page() {
return <p id="app-page">hello from app/docs/page</p>
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type import('next').NextConfig
*/
module.exports = {
basePath: '/docs',
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('pages router - prefetch of an app route that starts with the basePath', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
// `router.prefetch()` is a no-op in development, so the client router filter
// marker is only ever written by production builds.
;(isNextDev ? describe.skip : describe)('production mode', () => {
async function hoverAppLink(
browser: Awaited<ReturnType<typeof next.browser>>
) {
await browser.eval('window.beforeNav = 1')
await browser.elementById('app-link').moveTo()
await retry(async () => {
expect(
await browser.eval(
"window.next.router.components['/docs']?.__appRouter"
)
).toBe(true)
})
}
it('should hard navigate to the app route when the link is clicked', async () => {
const browser = await next.browser('/docs')
await hoverAppLink(browser)
await browser.elementById('app-link').click()
await browser.waitForElementByCss('#app-page')
expect(await browser.eval('window.beforeNav')).toBeUndefined()
expect(await browser.eval('location.pathname')).toBe('/docs/docs')
})
it('should keep shallow navigation working on the index page after prefetching the link', async () => {
const browser = await next.browser('/docs')
await hoverAppLink(browser)
await browser.elementById('tab-b').click()
await retry(async () => {
expect(await browser.elementById('tab').text()).toBe('b')
})
// a hard navigation would have reset the flag
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('location.pathname')).toBe('/docs')
expect(await browser.eval('location.search')).toBe('?tab=b')
})
})
})
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<>
<p id="pages-page">hello from pages/index</p>
<p id="tab">{router.query.tab || 'a'}</p>
<Link id="tab-b" href="/?tab=b" shallow>
tab b
</Link>
{/*
The app route `/docs` starts with the `basePath` `/docs`, so it is
served at `/docs/docs`. `next/link` hands the router the path without
the `basePath`, so stripping it again would turn `/docs` into `/`.
*/}
<Link id="app-link" href="/docs">
to app route
</Link>
</>
)
}
export default function Page() {
return <p id="app-page">hello from app/dashboard/page</p>
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type import('next').NextConfig
*/
module.exports = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
experimental: {
clientRouterFilterRedirects: true,
},
async redirects() {
return [
{
// French-only redirect: the English `/legacy` stays a pages route
source: '/fr/legacy',
destination: '/fr',
permanent: false,
locale: false,
},
]
},
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('pages router - prefetch marker keeps the effective locale', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
// `router.prefetch()` is a no-op in development, so the client router filter
// marker is only ever written by production builds.
;(isNextDev ? describe.skip : describe)('production mode', () => {
it('should keep the English navigation client-side after prefetching the French-only redirect', async () => {
const browser = await next.browser('/')
await browser.eval('window.beforeNav = 1')
await browser.elementById('fr-legacy-link').moveTo()
// wait until the prefetch has matched `/fr/legacy` and stored its marker
await retry(async () => {
expect(
await browser.eval(
"window.next.router.components['/fr/legacy']?.__appRouter"
)
).toBe(true)
})
await browser.elementById('en-legacy-link').click()
await browser.waitForElementByCss('#legacy-page')
// a hard navigation would have reset the flag
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('location.pathname')).toBe('/legacy')
})
})
})
import Link from 'next/link'
export default function Page() {
return (
<>
<p id="pages-page">hello from pages/index</p>
{/*
Prefetching this link evaluates the client router filter against
`/fr/legacy`, which matches the French-only redirect.
*/}
<Link id="fr-legacy-link" href="/legacy" locale="fr">
legacy (fr)
</Link>
<Link id="en-legacy-link" href="/legacy">
legacy (en)
</Link>
</>
)
}
export default function Page() {
return <p id="legacy-page">hello from pages/legacy</p>
}
export default function Page() {
return <p id="app-page">hello from app/dashboard/page</p>
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="app-modal-page">hello from app/modal/[id]/page</p>
}
/**
* @type import('next').NextConfig
*/
module.exports = {
async rewrites() {
return [
{
source: '/pretty',
destination: '/modal',
},
]
},
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('pages router - prefetch with `as` pointing at an app route', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
// `router.prefetch()` is a no-op in development, so the client router filter
// marker is only ever written by production builds.
;(isNextDev ? describe.skip : describe)('production mode', () => {
async function hoverLink(
browser: Awaited<ReturnType<typeof next.browser>>,
id: string,
markerKey: string
) {
await browser.eval('window.beforeNav = 1')
await browser.elementById(id).moveTo()
// wait until the prefetch has consulted the client router filter and
// stored the marker this test depends on
await retry(async () => {
expect(
await browser.eval(
`window.next.router.components[${JSON.stringify(markerKey)}]?.__appRouter`
)
).toBe(true)
})
}
it('should hard navigate to the app route when the link is clicked', async () => {
const browser = await next.browser('/')
await hoverLink(browser, 'app-link', '/dashboard')
await browser.elementById('app-link').click()
await browser.waitForElementByCss('#app-page')
expect(await browser.eval('window.beforeNav')).toBeUndefined()
expect(await browser.eval('location.pathname')).toBe('/dashboard')
})
it('should keep shallow navigation working on the static pages route after prefetching the link', async () => {
const browser = await next.browser('/')
await hoverLink(browser, 'app-link', '/dashboard')
await browser.elementById('tab-b').click()
await retry(async () => {
expect(await browser.elementById('tab').text()).toBe('b')
})
// a hard navigation would have reset the flag
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('location.search')).toBe('?tab=b')
})
it('should keep shallow navigation working on the dynamic pages route after prefetching the link', async () => {
const browser = await next.browser('/blog/first')
await hoverLink(browser, 'app-link', '/dashboard')
await browser.elementById('tab-b').click()
await retry(async () => {
expect(await browser.elementById('tab').text()).toBe('b')
})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.elementById('pages-page').text()).toBe(
'hello from pages/blog/[slug]'
)
// the props from getServerSideProps must survive the shallow navigation
expect(await browser.elementById('slug').text()).toBe('first')
expect(await browser.elementById('tab-b').getAttribute('href')).toBe(
'/blog/first?tab=b'
)
})
it('should hard navigate when the href route was flagged by the prefetch and `as` differs', async () => {
const browser = await next.browser('/')
// `/modal` is a pages route and the static prefix of `app/modal/[id]`
await hoverLink(browser, 'modal-link', '/modal')
// href is the flagged `/modal`, `as` is `/pretty` which the filter does
// not know. This must fall back to a hard navigation instead of reading
// the marker as component data.
await browser.elementById('push-pretty').click()
await browser.waitForElementByCss('#modal-page')
expect(await browser.eval('window.beforeNav')).toBeUndefined()
expect(await browser.eval('location.pathname')).toBe('/pretty')
})
it('should hard navigate when a config rewrite resolves to the flagged route', async () => {
const browser = await next.browser('/')
await hoverLink(browser, 'modal-link', '/modal')
// `/pretty` holds no marker, but the config rewrite resolves it to
// `/modal` after the first marker guard ran.
await browser.elementById('push-pretty-rewrite').click()
await browser.waitForElementByCss('#modal-page')
expect(await browser.eval('window.beforeNav')).toBeUndefined()
expect(await browser.eval('location.pathname')).toBe('/pretty')
expect(await browser.elementById('modal-page').text()).toBe(
'hello from pages/modal'
)
})
it('should keep the hash-only change client side when the prefetch flagged the current route', async () => {
// loaded through the config rewrite: the route is `/modal`, the URL is
// `/pretty`, so the filter does not skip `/modal` as the current path
const browser = await next.browser('/pretty')
await browser.eval('window.beforeNav = 1')
// the filter matches `/modal`, but the cache entry of the current
// route must survive the prefetch
await browser.elementById('prefetch-canonical').click()
await retry(async () => {
expect(await browser.elementById('prefetch-state').text()).toBe('done')
})
// a hash-only change does not call `getRouteInfo()`; it renders the
// cache entry of the current route directly and stays client side
await browser.elementById('hash-link').click()
await retry(async () => {
expect(await browser.eval('location.hash')).toBe('#section')
expect(await browser.eval('window.next.router.asPath')).toBe(
'/pretty#section'
)
})
expect(await browser.eval('window.beforeNav')).toBe(1)
// the props from getServerSideProps must still be rendered
expect(await browser.elementById('modal-page').text()).toBe(
'hello from pages/modal'
)
expect(await browser.eval('location.pathname')).toBe('/pretty')
})
})
})
import Link from 'next/link'
import { useRouter } from 'next/router'
export function getServerSideProps({ params }) {
return { props: { slug: params.slug } }
}
export default function Page({ slug }) {
const router = useRouter()
return (
<>
<p id="pages-page">hello from pages/blog/[slug]</p>
{/* server-provided prop: it must survive a shallow navigation */}
<p id="slug">{slug}</p>
{/* read from the router: a shallow navigation does not re-run getServerSideProps */}
<p id="tab">{router.query.tab || 'a'}</p>
<Link id="tab-b" href={`/blog/${slug}?tab=b`} shallow>
tab b
</Link>
{/*
"route as modal": href is the current dynamic route pattern with an
extra query param, `as` is an app route.
*/}
<Link
id="app-link"
href={{
pathname: router.pathname,
query: { ...router.query, modal: 1 },
}}
as="/dashboard"
shallow
>
to app route
</Link>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<>
<p id="pages-page">hello from pages/index</p>
<p id="tab">{router.query.tab || 'a'}</p>
<Link id="tab-b" href="/?tab=b" shallow>
tab b
</Link>
{/*
href stays on the current pages route, `as` is an app route.
Hovering it prefetches `href`/`as` and runs the client router filter
against `as`.
*/}
<Link id="app-link" href="/?modal=1" as="/dashboard" shallow>
to app route
</Link>
{/*
`/modal` is a pages route and also the static prefix of the app route
`app/modal/[id]`, so the dynamic client router filter flags it.
*/}
<Link id="modal-link" href="/modal">
to modal
</Link>
<button
id="push-pretty"
onClick={() => {
// href is the flagged pages route, `as` is an unrelated pretty URL
router.push('/modal', '/pretty')
}}
>
push /modal as /pretty
</button>
<button
id="push-pretty-rewrite"
onClick={() => {
// `/pretty` is rewritten to the flagged pages route `/modal` by a
// config rewrite. A button instead of a link so that no hover
// prefetch of `/pretty` itself writes a marker.
router.push('/pretty')
}}
>
push /pretty
</button>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useState } from 'react'
export function getServerSideProps() {
return { props: { title: 'hello from pages/modal' } }
}
// Served at `/modal` and, through the config rewrite, at `/pretty`.
export default function Page({ title }) {
const router = useRouter()
const [prefetchState, setPrefetchState] = useState('idle')
return (
<>
{/* server-provided prop: it is lost when a marker is rendered */}
<p id="modal-page">{title}</p>
{/*
When this page is loaded at `/pretty`, prefetching the canonical URL
evaluates the client router filter against `/modal`, the route of the
current page. The button reports when the prefetch has finished.
*/}
<button
id="prefetch-canonical"
onClick={async () => {
await router.prefetch('/modal')
setPrefetchState('done')
}}
>
prefetch canonical
</button>
<p id="prefetch-state">{prefetchState}</p>
<Link id="hash-link" href="#section">
to section
</Link>
<p id="section">section</p>
</>
)
}
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