Skip to content

Commit b420536

Browse files
authored
Fix false-positive nested-cache error for a short default profile (#95373)
Overriding the `default` `cacheLife` profile with a short cache life (the built-in `expire` is `INFINITE_CACHE`) makes every `'use cache'` without an inline `cacheLife()` inherit that short life. In this configuration the nested-`'use cache'` error, in both its short-`expire` and zero-`revalidate` variants, fired in two cases where it should not have. The error exists to catch a nested cache silently shortening an outer cache that has no explicit `cacheLife`, degrading it to a dynamic hole the developer did not choose. But with a short default profile, a single non-nested `'use cache'` already resolves to a short life with nothing nested, so the error fired with no nesting at all: in production this killed the build, and in development it threw on the request. And even for a genuinely nested cache, the warning is pointless here, because the default profile already makes every cache a dynamic hole, so there is no silent degradation to surprise the developer. The throw condition keyed on a short life that was not set through an inline `cacheLife()`, and a value inherited from the `default` profile is non-explicit, so it matched. This change additionally requires that a dynamic nested cache actually propagated its short life upward (`dynamicNestedCacheError` is set) and that the `default` profile is itself prerenderable. Otherwise the short-lived entry is omitted as a dynamic hole instead, exactly as an inline short `cacheLife()` already was. Genuine nesting under a prerenderable default profile still errors. The nesting condition also subsumes the dev-only private-cache exclusion: a private cache's `revalidate: 0` is forced by us rather than by a nested cache and never carries a nested error, so the explicit `kind !== 'private'` check is no longer needed.
1 parent 34dbafb commit b420536

6 files changed

Lines changed: 157 additions & 12 deletions

File tree

‎packages/next/src/server/use-cache/use-cache-wrapper.ts‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2262,6 +2262,23 @@ export async function cache(
22622262
rdcResult.entry.revalidate === 0 ||
22632263
rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE
22642264
) {
2265+
// The nested-cache error only makes sense when a dynamic nested cache
2266+
// actually shortened an outer cache that has no explicit `cacheLife`
2267+
// (`dynamicNestedCacheError` is set), and only when the app's default
2268+
// profile is itself prerenderable. If the default profile is already
2269+
// dynamic (`revalidate: 0` or an `expire` under the prerenderable
2270+
// minimum), every cache is omitted from prerenders by default, so
2271+
// there is no silent degradation to warn about. A short life from the
2272+
// default profile, or from a dev private cache's self-imposed
2273+
// `revalidate: 0` (which never carries a nested error), therefore
2274+
// stays a dynamic hole rather than erroring.
2275+
const defaultCacheLife = workStore.cacheLifeProfiles?.['default']
2276+
assertDefaultCacheLife(defaultCacheLife)
2277+
const shouldReportNestedCacheError =
2278+
rdcResult.dynamicNestedCacheError !== undefined &&
2279+
defaultCacheLife.revalidate !== 0 &&
2280+
defaultCacheLife.expire >= MIN_PRERENDERABLE_EXPIRE
2281+
22652282
switch (workUnitStore.type) {
22662283
case 'prerender':
22672284
// In a Dynamic I/O prerender, if the cache entry has
@@ -2271,7 +2288,10 @@ export async function cache(
22712288
// a dynamic hole that can be filled in during the resume with
22722289
// a potentially cached entry.
22732290
if (rdcResult.entry.revalidate === 0) {
2274-
if (rdcResult.hasExplicitRevalidate === false) {
2291+
if (
2292+
rdcResult.hasExplicitRevalidate === false &&
2293+
shouldReportNestedCacheError
2294+
) {
22752295
throw wrapAsInvalidDynamicUsageError(
22762296
new Error(nestedCacheZeroRevalidateErrorMessage, {
22772297
cause: rdcResult.dynamicNestedCacheError,
@@ -2284,7 +2304,10 @@ export async function cache(
22842304
'from static shell due to revalidate: 0'
22852305
)
22862306
} else {
2287-
if (rdcResult.hasExplicitExpire === false) {
2307+
if (
2308+
rdcResult.hasExplicitExpire === false &&
2309+
shouldReportNestedCacheError
2310+
) {
22882311
throw wrapAsInvalidDynamicUsageError(
22892312
new Error(nestedCacheShortExpireErrorMessage, {
22902313
cause: rdcResult.dynamicNestedCacheError,
@@ -2321,17 +2344,14 @@ export async function cache(
23212344
}
23222345
case 'request': {
23232346
if (process.env.NODE_ENV === 'development') {
2324-
// These throws force the user to make an explicit cache life
2325-
// decision on an outer cache that an inner cache would
2326-
// otherwise silently shorten. A dev private cache's
2327-
// `revalidate` is forced to 0 by us (not by a nested cache), so
2328-
// it's excluded from the first throw to avoid a false positive.
2329-
// Its forced `expire` is exactly MIN_PRERENDERABLE_EXPIRE, so
2330-
// it never trips the second throw and needs no exclusion there.
2347+
// These throws force an explicit cache life decision on an
2348+
// outer cache that a nested cache would otherwise silently
2349+
// shorten (see `shouldReportNestedCacheError` above). Otherwise
2350+
// the short-lived entry is deferred as a dynamic hole below.
23312351
if (
2332-
cacheContext.kind !== 'private' &&
23332352
rdcResult.entry.revalidate === 0 &&
2334-
rdcResult.hasExplicitRevalidate === false
2353+
rdcResult.hasExplicitRevalidate === false &&
2354+
shouldReportNestedCacheError
23352355
) {
23362356
throw wrapAsInvalidDynamicUsageError(
23372357
new Error(nestedCacheZeroRevalidateErrorMessage, {
@@ -2341,7 +2361,8 @@ export async function cache(
23412361
}
23422362
if (
23432363
rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE &&
2344-
rdcResult.hasExplicitExpire === false
2364+
rdcResult.hasExplicitExpire === false &&
2365+
shouldReportNestedCacheError
23452366
) {
23462367
throw wrapAsInvalidDynamicUsageError(
23472368
new Error(nestedCacheShortExpireErrorMessage, {
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: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Suspense } from 'react'
2+
import { cacheLife } from 'next/cache'
3+
4+
async function innerCache() {
5+
'use cache'
6+
cacheLife({ expire: 60 }) // short, under the prerenderable minimum
7+
return new Date().toISOString()
8+
}
9+
10+
async function outerCache() {
11+
'use cache'
12+
// No explicit `cacheLife`. Normally a short-lived cache nested inside an
13+
// outer cache without an explicit `cacheLife` errors during prerendering,
14+
// because the outer is silently degraded to a dynamic hole. Here it must not:
15+
// this app's default profile is itself dynamic (`expire: 0`), so every cache
16+
// is omitted from prerenders by default and there is nothing to warn about.
17+
return innerCache()
18+
}
19+
20+
async function NestedValue() {
21+
const value = await outerCache()
22+
return <p id="value">{value}</p>
23+
}
24+
25+
export default function Page() {
26+
return (
27+
<Suspense fallback={<p id="fallback">Loading...</p>}>
28+
<NestedValue />
29+
</Suspense>
30+
)
31+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Suspense } from 'react'
2+
3+
// A single, non-nested `'use cache'` with no inline `cacheLife()`. It inherits
4+
// the app's `default` profile, which is configured with `expire: 0`. That must
5+
// be treated exactly like an inline `cacheLife({ expire: 0 })`: a dynamic hole
6+
// excluded from the prerender, not a nested-cache misconfiguration. There is no
7+
// outer cache here, so the "nested inside another use cache" error must not
8+
// fire.
9+
async function CachedValue() {
10+
'use cache'
11+
return <p id="value">{new Date().toISOString()}</p>
12+
}
13+
14+
export default function Page() {
15+
return (
16+
<Suspense fallback={<p id="fallback">Loading...</p>}>
17+
<CachedValue />
18+
</Suspense>
19+
)
20+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* @type {import('next').NextConfig}
3+
*/
4+
const nextConfig = {
5+
cacheComponents: true,
6+
cacheLife: {
7+
// Override the built-in `default` profile so that every `'use cache'`
8+
// without an inline `cacheLife()` is dynamic (client-only) by default.
9+
// `revalidate` and `stale` are backfilled from the built-in default. This
10+
// is the configuration where a short default profile used to trip the
11+
// nested-cache "no explicit cacheLife" build error on a cache that isn't
12+
// nested at all.
13+
default: { expire: 0 },
14+
},
15+
}
16+
17+
module.exports = nextConfig
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { nextTestSetup } from 'e2e-utils'
2+
import { retry } from 'next-test-utils'
3+
4+
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
5+
6+
describe('use-cache-default-profile-expire-zero', () => {
7+
const { next } = nextTestSetup({
8+
files: __dirname,
9+
})
10+
11+
it('treats a short default cacheLife profile as a dynamic hole, not a nested-cache error', async () => {
12+
const browser = await next.browser('/')
13+
const initialValue = await browser.elementById('value').text()
14+
expect(initialValue).toMatch(isoDateRegExp)
15+
16+
// The short `expire` comes from the app's configured default profile, and
17+
// the cache is not nested inside another one, so the nested-cache "no
18+
// explicit cacheLife" error must never fire (in production it kills the
19+
// build; in dev it throws on the request).
20+
expect(next.cliOutput).not.toContain(
21+
'nested-use-cache-no-explicit-cachelife'
22+
)
23+
24+
// An `expire: 0` cache is a dynamic hole. In production it regenerates on
25+
// every request; in dev it is served warm across reloads and re-warmed in
26+
// the background. Either way, reloads converge to a fresh value.
27+
await retry(async () => {
28+
await browser.refresh()
29+
const value = await browser.elementById('value').text()
30+
expect(value).toMatch(isoDateRegExp)
31+
expect(value).not.toEqual(initialValue)
32+
})
33+
})
34+
35+
it('does not error when a short-lived cache is nested under a dynamic default profile', async () => {
36+
// A short-lived inner cache nested inside an outer cache without an
37+
// explicit `cacheLife` normally errors during prerendering. But because the
38+
// default profile is itself dynamic, the outer cache is omitted from
39+
// prerenders by default, so there is no silent degradation to warn about
40+
// and the nested cache renders as a dynamic hole instead.
41+
const browser = await next.browser('/nested')
42+
expect(await browser.elementById('value').text()).toMatch(isoDateRegExp)
43+
44+
expect(next.cliOutput).not.toContain(
45+
'nested-use-cache-no-explicit-cachelife'
46+
)
47+
})
48+
})

0 commit comments

Comments
 (0)