Skip to content

Commit 34dbafb

Browse files
authored
Skip saving expire: 0 values in the default cache handler in prod (#95363)
A `'use cache'` value with an explicit `cacheLife({ expire: 0 })` is expired the moment it is produced, so in production the `'use cache'` wrapper regenerates it on every read rather than serving the stored copy. The entry written to the cache handler is never served back, so persisting it is wasted work, and for a remote handler a needless round-trip and stored payload. Whether to skip that write is left to each cache handler. This change implements it in the built-in default handler; a custom handler can opt into the same behavior. Beyond the saved write, this makes `cacheLife({ expire: 0 })` a reliable way to keep a value out of the server-side cache handler, which covers two cases. In a conditional opt-out, a function with an otherwise normal cache life sets `expire: 0` for a result that is not worth persisting, for example when an upstream fetch errored. In client-only caching, a value is `expire: 0` by design so that it lives only in the client cache, via Cached Navigations or Runtime Prefetches when the route opts in, and never on the server. The skip is gated on `!process.env.__NEXT_DEV_SERVER`. In production the value is regenerated on every read regardless, so not storing it changes nothing that is served. Development keeps storing it, because the default handler's minimum retention serves the previously cached value across reloads while the entry re-warms in the background. A new `use-cache-default-handler-expire-zero` end-to-end test enables the default handler's debug logging (`NEXT_PRIVATE_DEBUG_CACHE`) and asserts on its `set()` decisions. Because the debug output is only available from the CLI, the test skips deployment.
1 parent 6f592de commit 34dbafb

5 files changed

Lines changed: 122 additions & 0 deletions

File tree

‎packages/next/src/server/lib/cache-handlers/default.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,18 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler {
162162
let size = 0
163163

164164
try {
165+
// In production an `expire: 0` entry is dynamic: the "use cache"
166+
// wrapper regenerates it on every read instead of serving the stored
167+
// copy, so persisting it would be a wasted write of a value that is
168+
// never served back. Skip storing it so the next read is a plain miss.
169+
// The dev server keeps it, because its minimum retention serves the
170+
// previously cached value across reloads. The `finally` below still
171+
// resolves the pending set.
172+
if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {
173+
debug?.('set', cacheKey, 'skipped dynamic entry')
174+
return
175+
}
176+
165177
const [value, clonedValue] = entry.value.tee()
166178
entry.value = value
167179
const reader = clonedValue.getReader()
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { ReactNode } from 'react'
2+
export default function Root({ children }: { children: ReactNode }) {
3+
return (
4+
<html>
5+
<body>{children}</body>
6+
</html>
7+
)
8+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { Suspense } from 'react'
2+
import { cacheLife } from 'next/cache'
3+
4+
// The id prop is serialized into the cache key, so tests can grep the built-in
5+
// default handler's debug output for a specific cache.
6+
async function ShortLivedCache({ id }: { id: string }) {
7+
'use cache'
8+
cacheLife('seconds') // expire: 60, short but non-zero, still saved
9+
return <p id="short-lived-value">{new Date().toISOString()}</p>
10+
}
11+
12+
async function ExpireZeroCache({ id }: { id: string }) {
13+
'use cache'
14+
cacheLife({ expire: 0 }) // dynamic, not saved by the default handler in prod
15+
return <p id="expire-zero-value">{new Date().toISOString()}</p>
16+
}
17+
18+
export default function Page() {
19+
return (
20+
<main>
21+
<Suspense>
22+
<ShortLivedCache id="short-lived" />
23+
</Suspense>
24+
<Suspense>
25+
<ExpireZeroCache id="expire-zero" />
26+
</Suspense>
27+
</main>
28+
)
29+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/**
2+
* @type {import('next').NextConfig}
3+
*/
4+
const nextConfig = {
5+
cacheComponents: true,
6+
}
7+
8+
module.exports = nextConfig
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { nextTestSetup } from 'e2e-utils'
2+
import { retry } from 'next-test-utils'
3+
4+
describe('use-cache-default-handler-expire-zero', () => {
5+
const { next, skipped, isNextStart } = nextTestSetup({
6+
files: __dirname,
7+
// Enable the built-in default cache handler's debug logging so we can
8+
// assert on its `set()` decisions in the CLI output. That output is not
9+
// available on deploy, so skip the deploy variant.
10+
env: { NEXT_PRIVATE_DEBUG_CACHE: '1' },
11+
skipDeployment: true,
12+
})
13+
14+
if (skipped) {
15+
return
16+
}
17+
18+
if (isNextStart) {
19+
it('does not save an expire:0 cache to the built-in default handler, but saves a short-lived one', async () => {
20+
const browser = await next.browser('/')
21+
expect(
22+
await browser.elementById('expire-zero-value').text()
23+
).toBeDateString()
24+
expect(
25+
await browser.elementById('short-lived-value').text()
26+
).toBeDateString()
27+
28+
// The default handler skips storing the `expire: 0` entry (it would never
29+
// be served back in production)...
30+
expect(next.cliOutput).toMatch(
31+
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] skipped dynamic entry/
32+
)
33+
34+
// ...and never reports it as stored.
35+
expect(next.cliOutput).not.toMatch(
36+
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] done/
37+
)
38+
39+
// The short-lived (`expire: 60`) cache is still stored.
40+
expect(next.cliOutput).toMatch(
41+
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"short-lived"}]\] done/
42+
)
43+
})
44+
} else {
45+
it('saves an expire:0 cache to the built-in default handler in dev', async () => {
46+
const browser = await next.browser('/')
47+
expect(
48+
await browser.elementById('expire-zero-value').text()
49+
).toBeDateString()
50+
51+
// In development the default handler keeps `expire: 0` entries (its
52+
// minimum retention serves them warm across reloads), so it stores rather
53+
// than skips.
54+
await retry(async () => {
55+
expect(next.cliOutput).toMatch(
56+
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] done/
57+
)
58+
})
59+
60+
expect(next.cliOutput).not.toMatch(
61+
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] skipped/
62+
)
63+
})
64+
}
65+
})

0 commit comments

Comments
 (0)