Unverified Commit 4731e968 authored by Benjamin Staneck's avatar Benjamin Staneck Committed by GitHub

Pages Router: do not return the `__appRouter` prefetch marker as route info on…

Pages Router: do not return the `__appRouter` prefetch marker as route info on shallow navigation (#98187)

### 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.

Runtime behaviour was also verified against the reproduction in
https://github.com/Stanzilla/next-pages-router-prefetch-bloom-filter-repro
by patching the compiled `router.js`. 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 5979942c
...@@ -2142,6 +2142,16 @@ export default class Router implements BaseRouter { ...@@ -2142,6 +2142,16 @@ export default class Router implements BaseRouter {
try { try {
let existingInfo: PrivateRouteInfo | undefined = this.components[route] let existingInfo: PrivateRouteInfo | undefined = this.components[route]
// `prefetch()` stores a `{ __appRouter: true }` marker in
// `this.components` when the client router filter matches a path. That
// marker is not route info: it has no `Component` and no `props`, so
// rendering it crashes `_app`. Treat it as a cache miss and fetch the
// route info again; `change()` is responsible for the hard navigation.
if (existingInfo && (existingInfo as any).__appRouter) {
existingInfo = undefined
}
if (routeProps.shallow && existingInfo && this.route === route) { if (routeProps.shallow && existingInfo && this.route === route) {
return existingInfo return existingInfo
} }
...@@ -2242,6 +2252,9 @@ export default class Router implements BaseRouter { ...@@ -2242,6 +2252,9 @@ export default class Router implements BaseRouter {
// Check again the cache with the new destination. // Check again the cache with the new destination.
existingInfo = this.components[route] existingInfo = this.components[route]
if (existingInfo && (existingInfo as any).__appRouter) {
existingInfo = undefined
}
if ( if (
routeProps.shallow && routeProps.shallow &&
existingInfo && existingInfo &&
......
export default function Page() {
return <p id="app-page">hello from app/blog/new/page</p>
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('pages router - shallow navigation with a stale app router marker', () => {
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 page props and state after a prefetch marked the current route', async () => {
const browser = await next.browser('/blog/first')
expect(await browser.elementById('slug').text()).toBe('first')
expect(await browser.elementById('tab').text()).toBe('a')
await browser.elementById('counter').click()
await retry(async () => {
expect(await browser.elementById('counter').text()).toBe('1')
})
// `href` is the route of this page, `as` is an app route. Without the
// fix the prefetch replaces the cached route info of this page with the
// `{ __appRouter: true }` marker.
await browser.elementById('prefetch-new').click()
await retry(async () => {
expect(await browser.elementById('prefetch-state').text()).toBe('done')
})
// a normal shallow link on the same page reads the cache entry
await browser.elementById('tab-b').click()
await retry(async () => {
expect(await browser.elementById('tab').text()).toBe('b')
})
// the props from getServerSideProps and the client state must survive
expect(await browser.elementById('slug').text()).toBe('first')
expect(await browser.elementById('counter').text()).toBe('1')
expect(await browser.eval('location.search')).toBe('?tab=b')
})
})
})
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useState } from 'react'
export function getServerSideProps({ params }) {
return { props: { slug: params.slug } }
}
export default function Page({ slug }) {
const router = useRouter()
const [count, setCount] = useState(0)
const [prefetchState, setPrefetchState] = useState('idle')
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 so the value does not depend on a data fetch */}
<p id="tab">{router.query.tab || 'a'}</p>
{/* client state: a hard navigation resets it */}
<button id="counter" onClick={() => setCount((c) => c + 1)}>
{count}
</button>
<p id="prefetch-state">{prefetchState}</p>
<button
id="prefetch-new"
onClick={async () => {
// "route as modal": `href` is the current dynamic route pattern with
// another slug, `as` is the app route `app/blog/new/page.js`. The
// client router filter matches `as`, and the prefetch stores its
// marker under the `href` pathname, the route of this page.
await router.prefetch('/blog/[slug]?slug=new', '/blog/new')
setPrefetchState('done')
}}
>
prefetch /blog/new
</button>
<Link id="tab-b" href={`/blog/${slug}?tab=b`} shallow>
tab b
</Link>
</>
)
}
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