Unverified Commit 469e513c authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Require explicit `cacheLife` on outer `"use cache"` when nesting short-lived caches (#89481)

This PR adds error handling for nested `"use cache"` where the inner
cache has a very short lifetime (zero `revalidate` or `expire` under 5
minutes) but the outer cache doesn't have an explicit `cacheLife()`
call.

Short-lived caches become "dynamic holes" that are excluded from
prerenders. When such a cache is nested inside another `"use cache"`
without an explicit `cacheLife`, the outer cache's lifetime would
silently become short too via
[propagation](https://nextjs.org/docs/app/api-reference/functions/cacheLife#nested-caching-behavior),
which can lead to unexpected behavior. To prevent this accidental
misconfiguration, Next.js now throws an error during prerendering,
requiring developers to explicitly declare their intent by adding
`cacheLife()` to the outer cache.

The implementation tracks whether `revalidate` and `expire` were
explicitly set via `hasExplicitRevalidate` and `hasExplicitExpire` flags
on the collected cache result. Errors are wrapped with
`wrapAsInvalidDynamicUsageError` to capture proper stack traces and
prevent userland try/catch from suppressing the build error.

Documentation has been updated with a new "Prerendering behavior"
section in the `cacheLife` API reference explaining how short-lived
caches become dynamic holes, and a "Nested short-lived caches"
subsection with examples showing how to fix the error.

closes NAR-761
parent 2842212c
...@@ -310,6 +310,8 @@ export default async function Page() { ...@@ -310,6 +310,8 @@ export default async function Page() {
} }
``` ```
> **Good to know:** A cache is considered "short-lived" when it uses the `seconds` profile, `revalidate: 0`, or `expire` under 5 minutes. Short-lived caches are automatically excluded from prerenders and become dynamic holes instead. If such a cache is nested inside another `use cache` without an explicit `cacheLife`, Next.js will throw an error during prerendering to prevent accidental misconfigurations. See [Prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
See the [`cacheLife` API reference](/docs/app/api-reference/functions/cacheLife) for available profiles and custom configuration options. See the [`cacheLife` API reference](/docs/app/api-reference/functions/cacheLife) for available profiles and custom configuration options.
### With runtime data ### With runtime data
......
...@@ -245,6 +245,12 @@ When you call revalidation functions from a Server Action ([`revalidateTag`](/do ...@@ -245,6 +245,12 @@ When you call revalidation functions from a Server Action ([`revalidateTag`](/do
> **Good to know**: The `stale` property in `cacheLife` differs from [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes). While `staleTimes` is a global setting affecting all routes, `cacheLife` allows per-function or per-route configuration. Updating `staleTimes.static` also updates the `stale` value of the `default` cache profile. > **Good to know**: The `stale` property in `cacheLife` differs from [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes). While `staleTimes` is a global setting affecting all routes, `cacheLife` allows per-function or per-route configuration. Updating `staleTimes.static` also updates the `stale` value of the `default` cache profile.
### Prerendering behavior
Caches with very short lifetimes — zero `revalidate` or `expire` under 5 minutes — are automatically excluded from prerenders and become "dynamic holes" instead. This includes the `seconds` profile.
This behavior allows you to mix static and dynamic content within the same page. Static parts are prerendered, while short-lived caches create boundaries where data is fetched at request time rather than build time. Use a `<Suspense>` boundary around dynamic caches to provide a fallback while content loads.
## Examples ## Examples
### Using preset profiles ### Using preset profiles
...@@ -420,6 +426,96 @@ export default async function Dashboard() { ...@@ -420,6 +426,96 @@ export default async function Dashboard() {
**It is recommended to specify an explicit `cacheLife`.** With explicit lifetime values, you can inspect a cached function or component and immediately know its behavior without tracing through nested caches. Without explicit lifetime values, the behavior becomes dependent on inner cache lifetimes, making it harder to reason about. **It is recommended to specify an explicit `cacheLife`.** With explicit lifetime values, you can inspect a cached function or component and immediately know its behavior without tracing through nested caches. Without explicit lifetime values, the behavior becomes dependent on inner cache lifetimes, making it harder to reason about.
#### Nested short-lived caches
As described in [Prerendering behavior](#prerendering-behavior), short-lived caches (zero `revalidate` or `expire` under 5 minutes) become dynamic holes excluded from prerenders.
When a short-lived cache is nested inside another `use cache` without an explicit `cacheLife`, the outer cache's lifetime would silently become short too via propagation. To prevent this accidental misconfiguration, Next.js throws an error during prerendering.
Note that the nested cache may not be obvious — it could be in an imported module or even a third-party dependency:
```tsx filename="components/short-lived-widget.tsx" highlight={5}
import { cacheLife } from 'next/cache'
export async function ShortLivedWidget() {
'use cache'
cacheLife('seconds')
const data = await fetchRealtimeData()
return <div>{data}</div>
}
```
Using this component from another `use cache` without an explicit `cacheLife` will error during prerendering:
```tsx filename="app/page.tsx"
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
// Error: no explicit cacheLife on outer cache
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}
```
To fix the error, add an explicit `cacheLife()` to the outer `use cache`:
**If you want the outer cache to remain static (prerendered)**, set a longer cache lifetime:
```tsx filename="app/page.tsx" highlight={6}
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
cacheLife('default') // Explicit cacheLife prevents the error
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}
```
**If you want the outer cache to also be short-lived**, explicitly set a short cache lifetime to confirm this is intentional. Wrap the component in a `<Suspense>` boundary to provide a fallback while content loads:
```tsx filename="app/page.tsx" highlight={7,17-19}
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
async function Content() {
'use cache: remote'
cacheLife('seconds') // Explicit cacheLife confirms this is intentionally short-lived
return (
<>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</>
)
}
export default function Page() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading...</p>}>
<Content />
</Suspense>
</div>
)
}
```
> **Note:** This example uses `"use cache: remote"` because runtime caching in serverless deployments doesn't persist across requests with the default in-memory cache. For self-hosted environments, `"use cache"` may be sufficient. See [Runtime caching considerations](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) for more details.
### Conditional cache lifetimes ### Conditional cache lifetimes
You can call `cacheLife` conditionally in different code paths to set different cache durations based on your application logic: You can call `cacheLife` conditionally in different code paths to set different cache durations based on your application logic:
......
---
title: Nested `"use cache"` with short cache lifetime requires explicit `cacheLife` on outer cache
---
## Why This Error Occurred
A `"use cache"` function or component with a very short cache lifetime (either `revalidate: 0` or `expire` under 5 minutes) is nested inside another `"use cache"` that doesn't have an explicit `cacheLife()` call.
When a nested cache has a very short lifetime, it would normally create a "dynamic hole" - meaning it's excluded from static prerenders. However, when this happens inside another `"use cache"` without an explicit `cacheLife`, the outer cache's lifetime silently becomes very short too (via propagation), which may be unintentional.
To prevent accidental misconfigurations, Next.js requires you to explicitly declare your intent by adding `cacheLife()` to the outer `"use cache"`.
## Possible Ways to Fix It
Add an explicit `cacheLife()` call to the outer `"use cache"` to declare your intent.
### Before
```jsx filename="components/short-lived-widget.js"
import { cacheLife } from 'next/cache'
export async function ShortLivedWidget() {
'use cache'
cacheLife('seconds')
const data = await fetchRealtimeData()
return <div>{data}</div>
}
```
```jsx filename="app/page.js"
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
// Error: no explicit cacheLife on outer cache
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}
```
### After: If you want the outer cache to remain static (prerendered)
Set a longer cache lifetime on the outer cache:
```jsx filename="app/page.js" highlight={6}
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
cacheLife('default') // Explicit cacheLife prevents the error
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}
```
### After: If you want the outer cache to also be short-lived
Explicitly set a short cache lifetime on the outer cache to confirm this is intentional. Wrap the component in a `<Suspense>` boundary to provide a fallback while content loads:
```jsx filename="app/page.js" highlight={7,17-19}
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
async function Content() {
'use cache: remote'
cacheLife('seconds') // Explicit cacheLife confirms this is intentionally short-lived
return (
<>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</>
)
}
export default function Page() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading...</p>}>
<Content />
</Suspense>
</div>
)
}
```
> **Note:** This example uses `"use cache: remote"` because runtime caching in serverless deployments doesn't persist across requests with the default in-memory cache. For self-hosted environments, `"use cache"` may be sufficient. See [Runtime caching considerations](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) for more details.
## Useful Links
- [`cacheLife` function](/docs/app/api-reference/functions/cacheLife)
- [`"use cache"` directive](/docs/app/api-reference/directives/use-cache)
- [Prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior)
- [Nested short-lived caches](/docs/app/api-reference/functions/cacheLife#nested-short-lived-caches)
...@@ -34,12 +34,16 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -34,12 +34,16 @@ describe('getDynamicHTMLPostponedState', () => {
prerenderResumeDataCache.cache.set( prerenderResumeDataCache.cache.set(
'1', '1',
Promise.resolve({ Promise.resolve({
value: streamFromString('hello'), entry: {
tags: [], value: streamFromString('hello'),
stale: 0, tags: [],
timestamp: 0, stale: 0,
expire: 300, timestamp: 0,
revalidate: 1, expire: 300,
revalidate: 1,
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
}) })
) )
...@@ -80,7 +84,7 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -80,7 +84,7 @@ describe('getDynamicHTMLPostponedState', () => {
expect(value).toBeDefined() expect(value).toBeDefined()
await expect(streamToString(value!.value)).resolves.toEqual('hello') await expect(streamToString(value!.entry.value)).resolves.toEqual('hello')
}) })
it('serializes a HTML postponed state without fallback params', async () => { it('serializes a HTML postponed state without fallback params', async () => {
......
...@@ -2,9 +2,9 @@ import { ...@@ -2,9 +2,9 @@ import {
arrayBufferToString, arrayBufferToString,
stringToUint8Array, stringToUint8Array,
} from '../app-render/encryption-utils' } from '../app-render/encryption-utils'
import type { CacheEntry } from '../lib/cache-handlers/types'
import type { CachedFetchValue } from '../response-cache/types' import type { CachedFetchValue } from '../response-cache/types'
import { DYNAMIC_EXPIRE } from '../use-cache/constants' import { DYNAMIC_EXPIRE } from '../use-cache/constants'
import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'
/** /**
* A generic cache store type that provides a subset of Map functionality * A generic cache store type that provides a subset of Map functionality
...@@ -34,19 +34,23 @@ export type DecryptedBoundArgsCacheStore = CacheStore<string> ...@@ -34,19 +34,23 @@ export type DecryptedBoundArgsCacheStore = CacheStore<string>
* Serialized format for "use cache" entries * Serialized format for "use cache" entries
*/ */
export interface UseCacheCacheStoreSerialized { export interface UseCacheCacheStoreSerialized {
value: string entry: {
tags: string[] value: string
stale: number tags: string[]
timestamp: number stale: number
expire: number timestamp: number
revalidate: number expire: number
revalidate: number
}
hasExplicitRevalidate: boolean | undefined
hasExplicitExpire: boolean | undefined
} }
/** /**
* A cache store specifically for "use cache" values that stores promises of * A cache store specifically for "use cache" values that stores promises of
* cache entries. * collected cache results (entry + metadata).
*/ */
export type UseCacheCacheStore = CacheStore<Promise<CacheEntry>> export type UseCacheCacheStore = CacheStore<Promise<CollectedCacheResult>>
/** /**
* Parses serialized cache entries into a UseCacheCacheStore * Parses serialized cache entries into a UseCacheCacheStore
...@@ -56,30 +60,34 @@ export type UseCacheCacheStore = CacheStore<Promise<CacheEntry>> ...@@ -56,30 +60,34 @@ export type UseCacheCacheStore = CacheStore<Promise<CacheEntry>>
export function parseUseCacheCacheStore( export function parseUseCacheCacheStore(
entries: Iterable<[string, UseCacheCacheStoreSerialized]> entries: Iterable<[string, UseCacheCacheStoreSerialized]>
): UseCacheCacheStore { ): UseCacheCacheStore {
const store = new Map<string, Promise<CacheEntry>>() const store = new Map<string, Promise<CollectedCacheResult>>()
for (const [ for (const [
key, key,
{ value, tags, stale, timestamp, expire, revalidate }, { entry, hasExplicitRevalidate, hasExplicitExpire },
] of entries) { ] of entries) {
store.set( store.set(
key, key,
Promise.resolve({ Promise.resolve({
// Create a ReadableStream from the Uint8Array entry: {
value: new ReadableStream<Uint8Array>({ // Create a ReadableStream from the Uint8Array
start(controller) { value: new ReadableStream<Uint8Array>({
// Enqueue the Uint8Array to the stream start(controller) {
controller.enqueue(stringToUint8Array(atob(value))) // Enqueue the Uint8Array to the stream
controller.enqueue(stringToUint8Array(atob(entry.value)))
// Close the stream // Close the stream
controller.close() controller.close()
}, },
}), }),
tags, tags: entry.tags,
stale, stale: entry.stale,
timestamp, timestamp: entry.timestamp,
expire, expire: entry.expire,
revalidate, revalidate: entry.revalidate,
},
hasExplicitRevalidate,
hasExplicitExpire,
}) })
) )
} }
...@@ -93,13 +101,13 @@ export function parseUseCacheCacheStore( ...@@ -93,13 +101,13 @@ export function parseUseCacheCacheStore(
* @returns A promise that resolves to an array of key-value pairs with serialized values * @returns A promise that resolves to an array of key-value pairs with serialized values
*/ */
export async function serializeUseCacheCacheStore( export async function serializeUseCacheCacheStore(
entries: IterableIterator<[string, Promise<CacheEntry>]>, entries: IterableIterator<[string, Promise<CollectedCacheResult>]>,
isCacheComponentsEnabled: boolean isCacheComponentsEnabled: boolean
): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> { ): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> {
return Promise.all( return Promise.all(
Array.from(entries).map(([key, value]) => { Array.from(entries).map(([key, value]) => {
return value return value
.then(async (entry) => { .then(async ({ entry, hasExplicitRevalidate, hasExplicitExpire }) => {
if ( if (
isCacheComponentsEnabled && isCacheComponentsEnabled &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE) (entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
...@@ -124,13 +132,17 @@ export async function serializeUseCacheCacheStore( ...@@ -124,13 +132,17 @@ export async function serializeUseCacheCacheStore(
return [ return [
key, key,
{ {
// Encode the value as a base64 string. entry: {
value: btoa(binaryString), // Encode the value as a base64 string.
tags: entry.tags, value: btoa(binaryString),
stale: entry.stale, tags: entry.tags,
timestamp: entry.timestamp, stale: entry.stale,
expire: entry.expire, timestamp: entry.timestamp,
revalidate: entry.revalidate, expire: entry.expire,
revalidate: entry.revalidate,
},
hasExplicitRevalidate,
hasExplicitExpire,
}, },
] satisfies [string, UseCacheCacheStoreSerialized] ] satisfies [string, UseCacheCacheStoreSerialized]
}) })
......
...@@ -15,12 +15,16 @@ function createMockedCache() { ...@@ -15,12 +15,16 @@ function createMockedCache() {
cache.cache.set( cache.cache.set(
'success', 'success',
Promise.resolve({ Promise.resolve({
value: streamFromString('value'), entry: {
tags: [], value: streamFromString('value'),
stale: 0, tags: [],
timestamp: 0, stale: 0,
expire: 300, timestamp: 0,
revalidate: 1, expire: 300,
revalidate: 1,
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
}) })
) )
...@@ -28,12 +32,16 @@ function createMockedCache() { ...@@ -28,12 +32,16 @@ function createMockedCache() {
cache.cache.set( cache.cache.set(
'dynamic-expire', 'dynamic-expire',
Promise.resolve({ Promise.resolve({
value: streamFromString('value'), entry: {
tags: [], value: streamFromString('value'),
stale: 0, tags: [],
timestamp: 0, stale: 0,
expire: 299, timestamp: 0,
revalidate: 1, expire: 299,
revalidate: 1,
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
}) })
) )
...@@ -41,12 +49,16 @@ function createMockedCache() { ...@@ -41,12 +49,16 @@ function createMockedCache() {
cache.cache.set( cache.cache.set(
'zero-revalidate', 'zero-revalidate',
Promise.resolve({ Promise.resolve({
value: streamFromString('value'), entry: {
tags: [], value: streamFromString('value'),
stale: 0, tags: [],
timestamp: 0, stale: 0,
expire: 300, timestamp: 0,
revalidate: 0, expire: 300,
revalidate: 0,
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
}) })
) )
...@@ -89,7 +101,7 @@ describe('stringifyResumeDataCache', () => { ...@@ -89,7 +101,7 @@ describe('stringifyResumeDataCache', () => {
) )
} else { } else {
expect(decompressed).toMatchInlineSnapshot( expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"dynamic-expire":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"zero-revalidate":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0}},"encryptedBoundArgs":{}}}"` `"{"store":{"fetch":{},"cache":{"success":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"hasExplicitRevalidate":true,"hasExplicitExpire":true},"dynamic-expire":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"hasExplicitRevalidate":true,"hasExplicitExpire":true},"zero-revalidate":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0},"hasExplicitRevalidate":true,"hasExplicitExpire":true}},"encryptedBoundArgs":{}}}"`
) )
} }
}) })
...@@ -117,7 +129,7 @@ describe('stringifyResumeDataCache', () => { ...@@ -117,7 +129,7 @@ describe('stringifyResumeDataCache', () => {
) )
} else { } else {
expect(decompressed).toMatchInlineSnapshot( expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"dynamic-expire":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"zero-revalidate":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0}},"encryptedBoundArgs":{}}}"` `"{"store":{"fetch":{},"cache":{"success":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"hasExplicitRevalidate":true,"hasExplicitExpire":true},"dynamic-expire":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"hasExplicitRevalidate":true,"hasExplicitExpire":true},"zero-revalidate":{"entry":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0},"hasExplicitRevalidate":true,"hasExplicitExpire":true}},"encryptedBoundArgs":{}}}"`
) )
} }
}) })
......
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
}
import { cacheLife } from 'next/cache'
async function innerCache() {
'use cache'
cacheLife({ expire: 60 }) // 1 minute, under the 5 minute threshold
return Math.random()
}
async function outerCache() {
'use cache'
// Explicitly not setting a `cacheLife` here means this will use the implicit
// default cache life, i.e. the shortest cache life of any nested 'use cache'
// will be applied, or the values of the 'default' profile if none are nested.
return innerCache()
}
export default async function Page() {
let result: number | undefined
try {
result = await outerCache()
} catch {}
return (
<>
<p>
This page tests that a nested "use cache" with low expire time inside
another "use cache" without explicit cacheLife throws an error during
prerendering.
</p>
<p>
The inner cache function is cached with a 60 second expire time. Such a
short-lived cache would normally create a dynamic hole and be excluded
from prerenders. However, when nested inside another 'use cache' that
doesn't specify an explicit `cacheLife`, this will error during
prerendering, instead of silently creating a dynamic hole. This is to
prevent accidental misconfigurations, where a developer may forget to
set an explicit `cacheLife` on an outer 'use cache' boundary, not
knowing that a nested 'use cache' is using a short-lived cache, which
would degrade the outer 'use cache' to a dynamic hole. If there is an
outer suspense boundary, this might not be noticeable, so we error
during prerendering to make sure the developer is aware of the situation
and picks an explicit `cacheLife` for the outer 'use cache'.
</p>
<p>
This page also tests that the error cannot be caught by userland code
(the try/catch above should NOT suppress the build error).
</p>
<p>Result: {result}</p>
</>
)
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
}
import { cacheLife } from 'next/cache'
async function innerCache() {
'use cache'
cacheLife({ revalidate: 0 })
return Math.random()
}
async function outerCache() {
'use cache'
// Explicitly not setting a `cacheLife` here means this will use the implicit
// default cache life, i.e. the shortest cache life of any nested 'use cache'
// will be applied, or the values of the 'default' profile if none are nested.
return innerCache()
}
export default async function Page() {
let result: number | undefined
try {
result = await outerCache()
} catch {}
return (
<>
<p>
This page tests that a nested "use cache" with zero revalidate inside
another "use cache" without explicit cacheLife throws an error during
prerendering.
</p>
<p>
The inner cache function is cached with a zero revalidate time. Such a
short-lived cache would normally create a dynamic hole and be excluded
from prerenders. However, when nested inside another 'use cache' that
doesn't specify an explicit `cacheLife`, this will error during
prerendering, instead of silently creating a dynamic hole. This is to
prevent accidental misconfigurations, where a developer may forget to
set an explicit `cacheLife` on an outer 'use cache' boundary, not
knowing that a nested 'use cache' is using a short-lived cache, which
would degrade the outer 'use cache' to a dynamic hole. If there is an
outer suspense boundary, this might not be noticeable, so we error
during prerendering to make sure the developer is aware of the situation
and picks an explicit `cacheLife` for the outer 'use cache'.
</p>
<p>
This page also tests that the error cannot be caught by userland code
(the try/catch above should NOT suppress the build error).
</p>
<p>Result: {result}</p>
</>
)
}
...@@ -4,7 +4,7 @@ async function getData() { ...@@ -4,7 +4,7 @@ async function getData() {
'use cache' 'use cache'
return fetch('https://next-data-api-endpoint.vercel.app/api/random', { return fetch('https://next-data-api-endpoint.vercel.app/api/random', {
next: { revalidate: 0 }, next: { revalidate: 1 },
}).then((res) => res.text()) }).then((res) => res.text())
} }
......
import { connection } from 'next/server'
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
async function revalidateZero() {
'use cache: remote'
cacheLife({ revalidate: 0 })
return new Date().toISOString()
}
async function lowExpire() {
'use cache: remote'
cacheLife({ expire: 5 })
return new Date().toISOString()
}
async function OuterCacheNoExplicit() {
'use cache: remote'
// No explicit cacheLife - this would error during prerendering, but is
// allowed at request time (after connection()).
return (
<>
<p>
<code>revalidate=0</code>:{' '}
<span id="revalidate-zero">{await revalidateZero()}</span>
</p>
<p>
<code>expire=5</code>: <span id="low-expire">{await lowExpire()}</span>
</p>
</>
)
}
async function OuterCacheExplicitShort() {
'use cache: remote'
// Explicit short cacheLife - excluded from prerender, becomes a dynamic hole.
cacheLife({ revalidate: 0, expire: 5 })
return (
<>
<p>
Explicit <code>revalidate=0</code>:{' '}
<span id="explicit-revalidate-zero">{await revalidateZero()}</span>
</p>
<p>
Explicit <code>expire=5</code>:{' '}
<span id="explicit-low-expire">{await lowExpire()}</span>
</p>
</>
)
}
async function OuterCacheExplicitLong() {
'use cache: remote'
// Explicit long cacheLife - included in prerender despite short-lived inner
// caches.
cacheLife('default')
return (
<>
<p>
Explicit long (<code>revalidate=0</code> inner):{' '}
<span id="explicit-long-revalidate-zero">{await revalidateZero()}</span>
</p>
<p>
Explicit long (<code>expire=5</code> inner):{' '}
<span id="explicit-long-low-expire">{await lowExpire()}</span>
</p>
</>
)
}
async function Dynamic() {
await connection()
return <OuterCacheNoExplicit />
}
export default async function Page() {
return (
<>
<p id="static">Static content</p>
<Suspense fallback={<p id="dynamic">Loading...</p>}>
<Dynamic />
</Suspense>
<Suspense fallback={<p>Loading explicit short...</p>}>
<OuterCacheExplicitShort />
</Suspense>
<OuterCacheExplicitLong />
</>
)
}
...@@ -486,6 +486,7 @@ describe('use-cache', () => { ...@@ -486,6 +486,7 @@ describe('use-cache', () => {
'/directive-in-node-modules/without-handler', '/directive-in-node-modules/without-handler',
'/draft-mode/with-cookies', '/draft-mode/with-cookies',
'/draft-mode/without-cookies', '/draft-mode/without-cookies',
'/fetch-revalidate',
'/form', '/form',
'/imported-from-client', '/imported-from-client',
'/logs', '/logs',
...@@ -639,9 +640,15 @@ describe('use-cache', () => { ...@@ -639,9 +640,15 @@ describe('use-cache', () => {
const browser = await next.browser('/fetch-revalidate') const browser = await next.browser('/fetch-revalidate')
const initialValue = await browser.elementByCss('#random').text() const initialValue = await browser.elementByCss('#random').text()
await browser.refresh()
expect(await browser.elementByCss('#random').text()).not.toBe(initialValue) // Revalidate is set to 1 second, so after waiting the value should change.
await retry(async () => {
await browser.refresh()
expect(await browser.elementByCss('#random').text()).not.toBe(
initialValue
)
})
}) })
it('should cache fetch without no-store', async () => { it('should cache fetch without no-store', async () => {
...@@ -1435,6 +1442,49 @@ describe('use-cache', () => { ...@@ -1435,6 +1442,49 @@ describe('use-cache', () => {
}) })
}) })
} }
it('should allow nested short-lived caches after connection()', async () => {
// Check the prerendered shell (no JS).
let browser = await next.browser('/short-lived-caches', {
disableJavaScript: true,
})
// Static content should be in the shell.
expect(await browser.elementById('static').text()).toBe('Static content')
// Explicit long cacheLife should be in the shell despite short-lived inner
// caches.
expect(
await browser.elementById('explicit-long-revalidate-zero').text()
).toBeDateString()
expect(
await browser.elementById('explicit-long-low-expire').text()
).toBeDateString()
// Now check with JS enabled to verify dynamic content loads.
browser = await next.browser('/short-lived-caches', {
pushErrorAsConsoleLog: true,
})
// Dynamic content should eventually render.
await retry(async () => {
// No explicit outer cacheLife (after connection()).
expect(
await browser.elementById('revalidate-zero').text()
).toBeDateString()
expect(await browser.elementById('low-expire').text()).toBeDateString()
// Explicit short cacheLife - excluded from prerender.
expect(
await browser.elementById('explicit-revalidate-zero').text()
).toBeDateString()
expect(
await browser.elementById('explicit-low-expire').text()
).toBeDateString()
})
await assertNoConsoleErrors(browser)
})
}) })
async function getSanitizedLogs(browser: Playwright): Promise<string[]> { async function getSanitizedLogs(browser: Playwright): Promise<string[]> {
......
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