Files
next.js/test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts
Hendrik LiebauandGitHub 286862e35b Fix stale dev 'use cache' for cookieless requests and route handlers (#96022)
In development, editing a file does not evict existing `'use cache'`
entries; an entry is invalidated only by re-keying, and the key includes
an HMR refresh hash. That hash was delivered through the
`__next_hmr_refresh_hash__` cookie, which the browser HMR client set
from each server-components change and sent back on later requests. Two
cases were therefore broken. First, any request that does not carry the
cookie (a `curl`, a plain `fetch`, a fresh browser profile, a second
device) served stale cached content after an edit, for both pages and
route handlers. Second, on Turbopack a route handler served stale
content even when fetched from a page whose HMR client had the cookie,
because a route-handler edit never advanced the hash there and so never
updated the cookie; on webpack that case happens to work, leaving only
cookieless route handlers broken.

The hash is server-authored to begin with (webpack's `stats.hash`,
Turbopack's `hmrHash` counter), so this change sources it directly on
the server and removes the cookie entirely. The hot-reloader exposes it,
and `base-server` attaches it to each request with `addRequestMeta`,
next to `serverComponentsHmrCache`, so it reaches every render,
including the internal Cache Components validation and warmup renders.
It is threaded onto the request store the same way
`serverComponentsHmrCache` is, so `'use cache'` is invalidated for every
client regardless of whether it ran the HMR client. Route handlers,
whose `NextRequest` does not carry request meta, receive it through the
app-route template's `renderOpts`.

Editing a route handler also has to advance the hash in the first place.
On webpack it already did, but on Turbopack the `app-route` entry wired
no change subscription, so a route edit recompiled the module without
advancing `hmrHash`; it now subscribes to the route endpoint so an edit
advances the hash without broadcasting a page refresh. That subscription
is also made the only thing that advances `hmrHash`: the
config-invalidation and server Fast Refresh reset paths previously
bumped it even without a content change, for example on a route's first
load, and with the hash now read synchronously instead of bounced back
through a cookie, such a bump would land between a route's cold write
and warm read and evict a still-valid entry. The getter returns the
counter unconditionally so the key is present and stable for every
request, matching webpack's always-present `stats.hash`.

With the cookie gone, the `hash` field on the `SERVER_COMPONENT_CHANGES`
HMR message has no remaining consumer, so it is dropped from the message
type and both bundlers.

This is a short-term stopgap until the granular implementation hash
(`codeHash` plus `runtimeEnvVars` plus the Next.js version) is used in
`next dev`, which invalidates server-authoritatively by construction and
will let this mechanism be removed.

> [!TIP]
> Best reviewed with hidden whitespace changes. 

closes NAR-894

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
2026-07-22 15:50:21 +02:00

160 lines
5.4 KiB
TypeScript

import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
describe('use-cache-custom-handler', () => {
const { next, skipped, isNextStart } = nextTestSetup({
files: __dirname,
// Skip deployment so we can test the custom cache handlers log output
skipDeployment: true,
})
if (skipped) return
let outputIndex: number
beforeEach(() => {
outputIndex = next.cliOutput.length
})
it('should use a modern custom cache handler if provided', async () => {
const browser = await next.browser(`/`)
const initialData = await browser.elementById('data').text()
expect(initialData).toMatch(isoDateRegExp)
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toContain('ModernCustomCacheHandler::refreshTags')
// In development the cache key carries a trailing HMR refresh hash element
// (absent in production), so the args array may be followed by an optional
// quoted hash.
expect(next.cliOutput.slice(outputIndex)).toMatch(
/ModernCustomCacheHandler::get \["(development|[A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\](,"[^"]+")?\] \[ '_N_T_\/layout', '_N_T_\/page', '_N_T_\/', '_N_T_\/index' \]/
)
expect(next.cliOutput.slice(outputIndex)).toMatch(
/ModernCustomCacheHandler::set \["(development|[A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\](,"[^"]+")?\]/
)
// Since no existing cache entry was retrieved, we don't need to call
// getExpiration() to compare the cache entries timestamp with the
// expiration of the implicit tags.
expect(cliOutput).not.toContain(`ModernCustomCacheHandler::getExpiration`)
// The data should be cached initially.
outputIndex = next.cliOutput.length
await browser.refresh()
let data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).toEqual(initialData)
// Now that a cache entry exists, we expect that getExpiration() is called
// to compare the cache entries timestamp with the expiration of the
// implicit tags.
expect(next.cliOutput.slice(outputIndex)).toContain(
`ModernCustomCacheHandler::getExpiration ["_N_T_/layout","_N_T_/page","_N_T_/","_N_T_/index"]`
)
// Because we use a low `revalidate` value for the "use cache" function, new
// data should be returned eventually.
await retry(
async () => {
await browser.refresh()
data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).not.toEqual(initialData)
},
10_000,
2_000
)
})
it('calls neither refreshTags nor getExpiration if "use cache" is not used', async () => {
await next.fetch(`/no-cache`)
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).not.toContain('ModernCustomCacheHandler::refreshTags')
expect(cliOutput).not.toContain(`ModernCustomCacheHandler::getExpiration`)
})
it('should revalidate after redirect using a modern custom cache handler', async () => {
const browser = await next.browser(`/`)
const initialData = await browser.elementById('data').text()
expect(initialData).toMatch(isoDateRegExp)
await browser.elementById('revalidate-redirect').click()
await retry(async () => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'ModernCustomCacheHandler::updateTags ["modern"]'
)
const data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).not.toEqual(initialData)
}, 5000)
})
it('should not call updateTags for a normal invocation', async () => {
await next.fetch(`/`)
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toInclude('ModernCustomCacheHandler::refreshTags')
expect(cliOutput).not.toInclude('ModernCustomCacheHandler::updateTags')
})
})
it('should not call getExpiration after an action', async () => {
const browser = await next.browser(`/`)
outputIndex = next.cliOutput.length
await browser.elementById('revalidate-tag').click()
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).not.toInclude('ModernCustomCacheHandler::getExpiration')
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::updateTags`,
1
)
})
})
if (isNextStart) {
it('should save a short-lived cache during prerendering at buildtime', async () => {
expect(next.cliOutput).toMatch(
/ModernCustomCacheHandler::set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"dynamic-cache"}]\]/
)
})
}
it('should dedupe nested caches across different outer cache scopes, and still propagate cache life/tags correctly', async () => {
await next.fetch('/nested')
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: inner`,
1
)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: outer1,inner`,
1
)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: outer2,inner`,
1
)
})
})
})