Unverified Commit b3118fca authored by Joseph's avatar Joseph Committed by GitHub

docs: recommend explicit cacheLife and clarify overriding built-in cache profiles (#95311)

- Lead use cache Revalidation with explicit cacheLife; split into
Time-based and On-demand.
- Recommend cacheLife in every use cache scope; drop "optional."
- Reorder cacheLife reference: Overriding before Custom; reword both.
- Document that overrides reach the generated cacheLife type signature.
- Add the override option to the config reference and migration guide.
parent c66662b9
...@@ -202,7 +202,7 @@ export default async function Page() { ...@@ -202,7 +202,7 @@ export default async function Page() {
} }
``` ```
> **Good to know**: If your `revalidate` value doesn't match a built-in [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile (`'seconds'`, `'minutes'`, `'hours'`, `'days'`, `'weeks'`, `'max'`), pick the closest one or define a [custom profile](/docs/app/api-reference/functions/cacheLife#custom-cache-profiles). > **Good to know**: If your `revalidate` value doesn't match a built-in [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile (`'seconds'`, `'minutes'`, `'hours'`, `'days'`, `'weeks'`, `'max'`), pick the closest one or define a [custom profile](/docs/app/api-reference/functions/cacheLife#custom-cache-profiles) to match your conventions. You can also [redefine a built-in profile](/docs/app/api-reference/functions/cacheLife#overriding-the-default-cache-profiles), including `default`, when its timings don't match your application's caching needs.
## `fetchCache` ## `fetchCache`
......
...@@ -279,30 +279,37 @@ The `x-nextjs-stale-time` response header communicates cache lifetime from serve ...@@ -279,30 +279,37 @@ The `x-nextjs-stale-time` response header communicates cache lifetime from serve
## Revalidation ## Revalidation
By default, `use cache` uses the `default` profile with these settings: Cached functions revalidate based on the `revalidate` and `expire` times in their `cacheLife` profile, or on-demand through tags. These two approaches are not mutually exclusive and are often paired:
- **stale**: 5 minutes (client-side) - **[Time-based](#time-based-revalidation)**: refresh automatically after a set duration with [`cacheLife`](/docs/app/api-reference/functions/cacheLife).
- **revalidate**: 15 minutes (server-side) - **[On-demand](#on-demand-revalidation)**: invalidate after a mutation with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) and [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) or [`updateTag`](/docs/app/api-reference/functions/updateTag).
- **expire**: Never expires by time
For example, a blog post that changes only when its author edits it can use a long `cacheLife` like `max` with a `cacheTag`, then invalidate on demand when the post is saved. A list of recent posts that updates throughout the day can use a shorter profile like `hours` to refresh on its own, without manual invalidation.
### Time-based revalidation
Set an explicit cache lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) in every `use cache` scope. It makes the cache behavior clear at the call site, instead of depending on the `default` profile or surrounding caches.
```tsx filename="lib/data.ts" ```tsx filename="lib/data.ts"
import { cacheLife } from 'next/cache'
async function getData() { async function getData() {
'use cache' 'use cache'
// Implicitly uses default profile cacheLife('hours') // Use built-in 'hours' profile
return fetch('/api/data') return fetch('/api/data')
} }
``` ```
### Customizing cache lifetime If you omit `cacheLife`, the `default` profile applies and the lifetime is no longer explicit at the call site:
Use the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) function to customize cache duration: - **stale**: 5 minutes (client-side)
- **revalidate**: 15 minutes (server-side)
- **expire**: never expires by time
```tsx filename="lib/data.ts" ```tsx filename="lib/data.ts"
import { cacheLife } from 'next/cache'
async function getData() { async function getData() {
'use cache' 'use cache'
cacheLife('hours') // Use built-in 'hours' profile // Implicitly uses the 'default' profile
return fetch('/api/data') return fetch('/api/data')
} }
``` ```
......
...@@ -45,7 +45,7 @@ Add a cache directive (for example, `use cache`) at the file level or at the top ...@@ -45,7 +45,7 @@ Add a cache directive (for example, `use cache`) at the file level or at the top
> **Good to know**: > **Good to know**:
> >
> - Calling `cacheLife` is optional. If omitted, a default cache lifetime is applied. > - We recommend setting a `cacheLife` in every `use cache` scope so its behavior is clear at the call site. Omitting it leaves the lifetime implicit (the `default` profile applies), which makes it harder to reason about, for example in [nested cached scopes](#nested-caching-behavior).
> - Call `cacheLife` in the same function or component where caching is defined. Avoid abstracting it into shared utilities so the cache behavior remains explicit and easy to reason about. > - Call `cacheLife` in the same function or component where caching is defined. Avoid abstracting it into shared utilities so the cache behavior remains explicit and easy to reason about.
> - If you call `cacheLife`, ensure only one call executes per function invocation. You can call it in different control flow branches, but only one should run per request. See the [conditional cache lifetimes](#conditional-cache-lifetimes) example. > - If you call `cacheLife`, ensure only one call executes per function invocation. You can call it in different control flow branches, but only one should run per request. See the [conditional cache lifetimes](#conditional-cache-lifetimes) example.
...@@ -145,11 +145,37 @@ If you don't specify a profile, Next.js uses the `default` profile. We recommend ...@@ -145,11 +145,37 @@ If you don't specify a profile, Next.js uses the `default` profile. We recommend
| `weeks` | Content updated weekly | 5 minutes | 1 week | 30 days | | `weeks` | Content updated weekly | 5 minutes | 1 week | 30 days |
| `max` | Stable content that rarely changes | 5 minutes | 30 days | 1 year | | `max` | Stable content that rarely changes | 5 minutes | 30 days | 1 year |
### Custom cache profiles ### Overriding the default cache profiles
The preset profiles map to familiar time periods (`seconds`, `minutes`, `hours`, `days`, `weeks`), alongside `default` and `max`. You can use these as they are, or redefine any of them, including `default` and `max`, in `next.config.ts`. The built-in names keep working with editor autocomplete.
Define reusable cache profiles in your `next.config.ts` file: Redefining a built-in is a supported pattern, but document it in your project so a call like `cacheLife('hours')` reflects the values you set, not the presets. The time-named profiles carry an intuitive expectation (`days` reads as roughly 24 hours), so redefining them is more likely to surprise a reader than redefining `default` or `max`, which don't imply a specific duration. An equally valid approach is to define your own [custom profile](#custom-cache-profiles) rather than overloading a built-in name.
Redefining `default` also changes the lifetime applied when a `use cache` scope calls no `cacheLife`. The example below sets `default` to a one hour revalidate:
```ts filename="next.config.ts" ```ts filename="next.config.ts"
const nextConfig = {
cacheComponents: true,
cacheLife: {
// Redefine the 'default' profile
default: {
stale: 300, // 5 minutes
revalidate: 3600, // 1 hour
expire: 86400, // 1 day
},
},
}
export default nextConfig
```
> **Good to know:** The `cacheLife` function's type signature is generated from `next.config.ts` during `next dev`, `next build`, or [`next typegen`](/docs/app/api-reference/cli/next#next-typegen-options), so an overridden profile's editor autocomplete and JSDoc hint reflect the values you set, not the presets.
### Custom cache profiles
Define reusable cache profiles with your own names in `next.config.ts`:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
...@@ -195,30 +221,6 @@ export default async function Page() { ...@@ -195,30 +221,6 @@ export default async function Page() {
} }
``` ```
### Overriding the default cache profiles
While the default cache profiles provide a useful way to think about how fresh or stale any given part of cacheable output can be, you may prefer different named profiles to better align with your applications caching strategies.
You can override the default named cache profiles by creating a new configuration with the same name as the defaults.
The example below shows how to override the default `"days"` cache profile:
```ts filename="next.config.ts"
const nextConfig = {
cacheComponents: true,
cacheLife: {
// Override the 'days' profile
days: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
},
},
}
export default nextConfig
```
### Inline cache profiles ### Inline cache profiles
For one-off cases, pass a profile object directly to `cacheLife`: For one-off cases, pass a profile object directly to `cacheLife`:
......
...@@ -70,6 +70,8 @@ export async function getCachedData() { ...@@ -70,6 +70,8 @@ export async function getCachedData() {
} }
``` ```
You can also override a built-in profile by defining one with the same name (`default`, `seconds`, `minutes`, `hours`, `days`, `weeks`, or `max`). See [Overriding the default cache profiles](/docs/app/api-reference/functions/cacheLife#overriding-the-default-cache-profiles).
## Reference ## Reference
The configuration object has key values with the following format: The configuration object has key values with the following format:
......
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