Unverified Commit a7877d77 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Bugfix: Incorrect search params stored in cache (#94144)

The route cache write was keying entries on `renderedSearch` — the
search string the server actually used to render the page — but lookups
use the requested URL's search component. These two are not equivalent:
for any search-invariant route (e.g. a static page), `renderedSearch` is
`''` regardless of what the request URL carried.

The result was that a request for `/a?foo=bar` against a static page
parked the cache entry at vary path `(/a, '', null)` — the same slot a
clean `/a` lookup keys to. The entry's stored `canonicalUrl` came from
the requesting URL (`/a?foo=bar`), so a later `router.push('/a')` or
`router.replace('/a')` would hit that slot and restore the stale search
string into the browser address bar, `window.location`, and
`useSearchParams()`.

The fix keys cache writes on the request URL's search, not
`renderedSearch`. Entries now sit at the slot keyed by the request that
wrote them, so a lookup for a different search variant doesn't find
them.

Regression test covers the reproduction from the user repo linked in the
bug reports.

Closes #91658
Closes #92187

<!-- NEXT_JS_LLM_PR -->
parent 67d5f961
......@@ -106,6 +106,7 @@ export function createInitialRouterState({
discoverKnownRoute(
Date.now(),
location.pathname,
location.search as NormalizedSearch,
null, // nextUrl — initial render is never an interception
null, // No pending entry
initialRouteTree,
......
......@@ -1636,6 +1636,7 @@ function dispatchRetryDueToTreeMismatch(
discoverKnownRoute(
now,
retryUrl.pathname,
retryUrl.search as NormalizedSearch,
retryNextUrl,
null,
seed.routeTree,
......
......@@ -485,6 +485,7 @@ export function serverActionReducer(
discoverKnownRoute(
now,
redirectUrl.pathname,
redirectUrl.search as NormalizedSearch,
nextUrl,
null, // No pending entry
redirectSeed.routeTree,
......
......@@ -1141,6 +1141,7 @@ export function fulfillRouteCacheEntry(
export function writeRouteIntoCache(
now: number,
pathname: NormalizedPathname,
search: NormalizedSearch,
nextUrl: string | null,
tree: RouteTree,
metadataVaryPath: PageVaryPath,
......@@ -1158,10 +1159,9 @@ export function writeRouteIntoCache(
canonicalUrl,
supportsPerSegmentPrefetching
)
const renderedSearch = fulfilledEntry.renderedSearch
const varyPath = getFulfilledRouteVaryPath(
pathname,
renderedSearch,
search,
nextUrl as NormalizedNextUrl | null,
couldBeIntercepted
)
......@@ -1797,6 +1797,7 @@ export async function fetchRouteOnCacheMiss(
discoverKnownRoute(
Date.now(),
pathname,
search,
nextUrl,
entry,
routeTree,
......@@ -1854,6 +1855,7 @@ export async function fetchRouteOnCacheMiss(
routeIsPPREnabled,
headVaryParams,
pathname,
search,
nextUrl
)
}
......@@ -2347,6 +2349,7 @@ function writeDynamicTreeResponseIntoCache(
routeIsPPREnabled: boolean,
headVaryParams: VaryParams | null,
originalPathname: string,
originalSearch: NormalizedSearch,
nextUrl: string | null
): void {
const renderedSearch = getRenderedSearch(response)
......@@ -2395,6 +2398,7 @@ function writeDynamicTreeResponseIntoCache(
discoverKnownRoute(
now,
originalPathname,
originalSearch,
nextUrl,
entry,
routeTree,
......
......@@ -437,6 +437,7 @@ async function navigateToUnknownRoute(
discoverKnownRoute(
now,
url.pathname,
url.search as NormalizedSearch,
nextUrl,
null, // No pending entry
navigationSeed.routeTree,
......
......@@ -197,6 +197,7 @@ let knownRouteTreeRoot: KnownRoutePart = createEmptyPart()
export function discoverKnownRoute(
now: number,
pathname: string,
search: NormalizedSearch,
nextUrl: string | null,
pendingEntry: PendingRouteCacheEntry | null,
routeTree: RouteTree,
......@@ -235,6 +236,7 @@ export function discoverKnownRoute(
fulfilledEntry,
now,
pathname,
search,
nextUrl,
tree,
metadataVaryPath,
......@@ -256,6 +258,7 @@ export function discoverKnownRoute(
null,
now,
pathname,
search,
nextUrl,
tree,
metadataVaryPath,
......@@ -276,6 +279,7 @@ function handleMismatchDueToRewrite(
existingEntry: FulfilledRouteCacheEntry | null,
now: number,
pathname: string,
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree,
metadataVaryPath: PageVaryPath,
......@@ -289,6 +293,7 @@ function handleMismatchDueToRewrite(
return writeRouteIntoCache(
now,
pathname as NormalizedPathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -344,6 +349,7 @@ function discoverKnownRoutePart(
// These are passed through unchanged for entry creation at the leaf
now: number,
pathname: string,
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree,
metadataVaryPath: PageVaryPath,
......@@ -370,6 +376,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -409,6 +416,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -429,6 +437,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -496,6 +505,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -517,6 +527,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -534,6 +545,7 @@ function discoverKnownRoutePart(
existingEntry,
now,
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......@@ -565,6 +577,7 @@ function discoverKnownRoutePart(
entry = writeRouteIntoCache(
now,
pathname as NormalizedPathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
......
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="dummy-page-1">Dummy Page 1</h1>
<Link id="link-to-dummy-2" href="/dummy-page-2">
Go to dummy page 2
</Link>
</>
)
}
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<>
<h1 id="dummy-page-2">Dummy Page 2</h1>
<button id="go-home" onClick={() => router.replace('/')}>
Go to home
</button>
</>
)
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<>
<h1 id="home">Home</h1>
<Link id="link-to-dummy-1" href="/dummy-page-1">
Go to dummy page 1
</Link>
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
reactStrictMode: true,
experimental: {
// Disabling prefetch inlining avoids the `InliningHintsStale` marker
// that would otherwise immediately expire the initial-state route
// cache entry. The bug under test depends on that entry sticking
// around long enough to be read by `router.replace('/')`.
prefetchInlining: false,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('segment cache - stale search params on replace regression', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// Regression test for https://github.com/vercel/next.js/issues/91658.
//
// Reproduction is taken directly from the user's report and from their
// minimal repro at https://github.com/dlehmhus/next-router-replace-bug:
//
// 1. Build and start the application.
// 2. Open `/?query=param` directly in the browser (full page load).
// 3. Click `<Link href="/dummy-page-1">` — navigates to /dummy-page-1.
// 4. Click `<Link href="/dummy-page-2">` — navigates to /dummy-page-2.
// 5. Click the button that calls `router.replace('/')`.
//
// Expected: URL is `/` with no search string.
// Buggy: URL becomes `/?query=param` — the search string from the
// original page load is restored.
it('router.replace to a clean URL clears the search params from the initial page load', async () => {
const browser = await next.browser('/?query=param')
await browser.waitForElementByCss('#home')
await browser.elementById('link-to-dummy-1').click()
await browser.waitForElementByCss('#dummy-page-1')
await browser.elementById('link-to-dummy-2').click()
await browser.waitForElementByCss('#dummy-page-2')
await browser.elementById('go-home').click()
await browser.waitForElementByCss('#home')
await retry(async () => {
const url = new URL(await browser.url())
expect(url.pathname).toBe('/')
expect(url.search).toBe('')
})
})
})
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