Unverified Commit f1a7e1db authored by Arya's avatar Arya Committed by GitHub

fix(use-cache): track root params read in "use cache" as vary params (#98674)

### What?

A `"use cache"` segment that reads a root param via `next/root-params`
is reused after a client-side navigation that changes that param. With
`cacheComponents`, a production build and `<Link prefetch={false}>`:
open `/en`, click `de`. URL, `usePathname()` and layout say `de`; the
page segment still says `en`.

### Why?

Inside a `"use cache"` scope, `getRootParam` only records the name in
`readRootParamNames`, which keys the server cache entry. Nothing
forwards it to the response's root vary params, so the client re-keys
the segment as `Fallback` and reuses it for every locale. `await params`
masks the bug because serializing the cache key touches the tracked
params object.

### How?

`propagateCacheEntryMetadata` adds `readRootParamNames` to the outer
store's root vary accumulator when one exists. The client already unions
root vary params into every segment.

Not covered: `"use cache: private"` root-param reads are only tracked in
dev, so the same reuse can still happen there in production.

Review order: `use-cache-wrapper.ts` is the whole change (one block
after the propagation switch, plus the doc note above
`maybePropagateCacheEntryMetadata`). The fixture adds a `[locale]` route
under the existing `vary-params` app.

Test: `vary-params.test.ts`, "does not reuse a "use cache" segment
across root param values", fails with `Received: "Locale: en"` before
the fix. Reporter's repro renders `de` after navigation on the patched
package.

Fixes #98493

cc @unstubbable @lubieowoce (use cache vary params)

<!-- NEXT_JS_LLM -->
parent c92542c9
......@@ -28,6 +28,7 @@ import type {
import {
getHmrRefreshHash,
getResumeDataCache,
getVaryParamsAccumulator,
workUnitAsyncStorage,
getDraftModeProviderForCacheScope,
getCacheSignal,
......@@ -35,6 +36,7 @@ import {
getServerComponentsHmrCache,
willConsumerServerCache,
} from '../app-render/work-unit-async-storage.external'
import { accumulateVaryParam } from '../app-render/vary-params'
import {
applyOwnerStack,
......@@ -1029,6 +1031,17 @@ function propagateCacheEntryMetadata(
cacheContext.outerWorkUnitStore satisfies never
}
}
if (metadata.readRootParamNames) {
const varyParamsAccumulator = getVaryParamsAccumulator(
cacheContext.outerWorkUnitStore
)
if (varyParamsAccumulator) {
for (const paramName of metadata.readRootParamNames) {
accumulateVaryParam(varyParamsAccumulator.rootParams, paramName)
}
}
}
}
/**
......@@ -1041,10 +1054,12 @@ function propagateCacheEntryMetadata(
* `propagateCacheEntryMetadata` is called unconditionally (after the omission
* checks have already filtered out short-lived entries).
*
* Note: Root param names are only propagated when the outer context is a
* `cache` store (i.e. an enclosing `"use cache"` function), which is never
* deferred. For prerender contexts, root param names are tracked separately
* via `addKnownRootParamNames` in the resume data cache read path.
* Note: Root param names are only propagated to `readRootParamNames` when the
* outer context is a `cache` store (i.e. an enclosing `"use cache"` function),
* which is never deferred. For prerender contexts, root param names are
* tracked separately via `addKnownRootParamNames` in the resume data cache
* read path. They're also recorded as root vary params (if tracked), so that
* the client doesn't reuse the segment across different values.
*/
function maybePropagateCacheEntryMetadata(
cacheContext: CacheContext,
......
'use cache'
import Link from 'next/link'
import { locale } from 'next/root-params'
export async function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'de' }]
}
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang={await locale()}>
<body>
<Link href="/cached-root-params/en" prefetch={false}>
en
</Link>
<Link href="/cached-root-params/de" prefetch={false}>
de
</Link>
{children}
</body>
</html>
)
}
'use cache'
import { locale } from 'next/root-params'
export default async function Page() {
return <div id="cached-root-param">{`Locale: ${await locale()}`}</div>
}
......@@ -822,4 +822,30 @@ describe('segment cache - vary params', () => {
{ includes: 'Root param page content - param: bbb' }
)
})
it('does not reuse a "use cache" segment across root param values', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/cached-root-params/en', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
expect(await browser.elementById('cached-root-param').text()).toBe(
'Locale: en'
)
// Not prefetched, so the navigation fetches /de and must not reuse the
// page segment cached for /en.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/cached-root-params/de"]'
)
await link.click()
})
expect(await browser.elementById('cached-root-param').text()).toBe(
'Locale: de'
)
})
})
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