cacheLife
了解如何使用 cacheLife 函数为缓存的函数或组件设置缓存过期时间。
cacheLife 函数用于设置函数或组件的缓存生命周期。它应与 use cache 指令一起使用,并且位于函数或组件的作用域内。
用法#
基本设置#
要使用 cacheLife,请先在 next.config.js 文件中启用 cacheComponents 标志:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfigconst nextConfig = {
cacheComponents: true,
}
module.exports = nextConfigcacheLife 只能在缓存指令作用域内使用。
在文件级别或异步函数或组件的顶部添加缓存指令(例如 use cache)。
cacheLife 不能在模块作用域中使用。在文件顶层调用它会抛出错误。
小知识:
使用预设配置#
Next.js 提供了预设的缓存配置,涵盖常见的缓存需求。每个配置都会平衡三个因素:
- 用户在多长时间内看到缓存内容而不检查更新(客户端)
- 服务器上多久生成一次新内容
- 旧内容何时完全过期
根据内容变化的频率选择配置:
seconds- 实时数据(股票价格、实时比分)minutes- 频繁更新(社交媒体信息流、新闻)hours- 每天多次更新(产品库存、天气)days- 每天更新(博客文章、新闻文章)weeks- 每周更新(播客、新闻简报)max- 很少变化(法律页面、归档内容)
导入 cacheLife 并传入配置名称:
'use cache'
import { cacheLife } from 'next/cache'
export default async function BlogPage() {
cacheLife('days') // 博客内容每天更新
const posts = await getBlogPosts()
return <div></div>
}配置名称告诉 Next.js 如何缓存整个函数的输出。如果不调用 cacheLife,则使用 default 配置。有关时间细节,请参阅预设缓存配置。
参考#
缓存配置属性#
缓存配置通过三个时间属性控制缓存行为:
stale:客户端在不检查服务器的情况下可以使用缓存数据多长时间revalidate:经过此时间后,下一个请求将触发后台刷新expire:经过此时间且没有请求后,下一个请求将等待新内容
stale#
客户端: 客户端在不检查服务器的情况下可以使用缓存数据多长时间。
在此期间,客户端路由器会立即显示缓存内容,而无需任何网络请求。此期限到期后,路由器必须在下一次导航或请求时向服务器检查。这提供了来自客户端缓存的即时页面加载,但数据可能已过时。
- 如果省略,默认为
default配置的stale值(5 分钟,请参阅staleTimes) - 还决定内容是否可以成为路由 App Shell 的一部分。请参阅预渲染行为。
cacheLife({ stale: 300 }) // 5 分钟revalidate#
服务器在后台重新生成缓存内容的频率。
- 当在此期限之后有请求到达时,服务器会:
- 立即提供缓存版本(如果有)
- 在后台重新生成内容
- 用新内容更新缓存
- 类似于增量静态再生成(Incremental Static Regeneration,ISR)
- 如果省略,默认为
default配置的revalidate值(15 分钟)
cacheLife({ revalidate: 900 }) // 15 分钟expire#
服务器必须重新生成缓存内容之前的最长时间。
- 在此期限后没有流量的情况下,服务器会在下一个请求时同步重新生成内容
- 当你同时设置
revalidate和expire时,expire必须长于revalidate。Next.js 会对此进行验证,并对无效配置抛出错误。 - 如果省略,默认为
default配置的expire值(永不过期)
cacheLife({ expire: 3600 }) // 1 小时预设缓存配置#
如果不指定配置,Next.js 会使用 default 配置。我们建议显式设置配置,以使缓存行为清晰。
| 配置 | 使用场景 | stale | revalidate | expire |
|---|---|---|---|---|
default | 标准内容 | 5 分钟 | 15 分钟 | 永不过期 |
seconds | 实时数据 | 30 秒 | 1 秒 | 1 分钟 |
minutes | 频繁更新的内容 | 5 分钟 | 1 分钟 | 1 小时 |
hours | 每天多次更新的内容 | 5 分钟 | 1 小时 | 1 天 |
days | 每天更新的内容 | 5 分钟 | 1 天 | 1 周 |
weeks | 每周更新的内容 | 5 分钟 | 1 周 | 30 天 |
max | 很少变化的稳定内容 | 5 分钟 | 30 天 | 1 年 |
覆盖默认缓存配置#
预设配置对应熟悉的时间段(seconds、minutes、hours、days、weeks),以及 default 和 max。你可以按原样使用它们,也可以在 next.config.ts 中重新定义其中任何一个,包括 default 和 max。内置名称仍然可以与编辑器自动补全一起使用。
重新定义内置配置是一种受支持的模式,但请在你的项目中记录下来,以便像 cacheLife('hours') 这样的调用反映的是你设置的值,而不是预设值。以时间命名的配置带有直观的预期(days 读作大约 24 小时),因此重新定义它们比重新定义不表示特定时长的 default 或 max 更容易让读者感到意外。同样有效的做法是定义你自己的自定义配置,而不是重载内置名称。
重新定义 default 还会更改当 use cache 作用域不调用 cacheLife 时应用的生命周期。下面的示例将 default 设置为一小时重新验证:
const nextConfig = {
cacheComponents: true,
cacheLife: {
// 重新定义 'default' 配置
default: {
stale: 300, // 5 分钟
revalidate: 3600, // 1 小时
expire: 86400, // 1 天
},
},
}
export default nextConfig小知识:
cacheLife函数的类型签名是在next dev、next build或next typegen期间从next.config.ts生成的,因此被覆盖配置的编辑器自动补全和 JSDoc 提示反映的是你设置的值,而不是预设值。
自定义缓存配置#
在 next.config.ts 中使用你自己的名称定义可重用的缓存配置:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
cacheLife: {
biweekly: {
stale: 60 * 60 * 24 * 14, // 14 天
revalidate: 60 * 60 * 24, // 1 天
expire: 60 * 60 * 24 * 14, // 14 天
},
},
}
export default nextConfigconst nextConfig = {
cacheComponents: true,
cacheLife: {
biweekly: {
stale: 60 * 60 * 24 * 14, // 14 天
revalidate: 60 * 60 * 24, // 1 天
expire: 60 * 60 * 24 * 14, // 14 天
},
},
}
module.exports = nextConfig上面的示例缓存 14 天,每天检查更新,并在 14 天后使缓存过期。然后你可以在整个应用中通过名称引用此配置:
小知识:自定义配置中任何省略的属性都会继承
default配置。这也适用于直接传递给cacheLife()的内联配置对象。
'use cache'
import { cacheLife } from 'next/cache'
export default async function Page() {
cacheLife('biweekly')
return <div>Page</div>
}内联缓存配置#
对于一次性情况,直接将配置对象传递给 cacheLife:
'use cache'
import { cacheLife } from 'next/cache'
export default async function Page() {
cacheLife({
stale: 3600,
revalidate: 900,
expire: 86400,
})
return <div>Page</div>
}内联配置仅适用于特定的函数或组件。对于可重用的配置,请在 next.config.ts 中定义自定义配置。
使用空对象的 cacheLife({}) 会应用 default 配置的值。
客户端缓存行为#
stale 属性控制的是客户端缓存,而不是 Cache-Control 标头:
- 服务器通过
x-nextjs-stale-time响应标头发送 stale 时间 - 客户端路由器使用此值来确定何时重新验证
- 强制最短 30 秒,以确保预取的链接保持可用
这个 30 秒的下限可以防止预取数据在用户点击链接之前过期。它仅适用于基于时间的过期。
从 Server Action 调用重新验证函数可以在 stale 时间到达之前清除客户端缓存条目:
revalidatePath、updateTag和revalidateTag如果使用解析为expire: 0的缓存配置(包括内联{ expire: 0 }),会清除预取的路由以及为前进/后退导航保留的页面。refresh会清除为前进/后退导航保留的页面,并保留其他预取的路由。- 使用解析为非零
expire值的缓存配置(如'max')的revalidateTag不会改变客户端缓存。
小知识:
cacheLife中的stale属性与staleTimes不同。staleTimes是影响所有路由的全局设置,而cacheLife允许按函数或按路由进行配置。更新staleTimes.static也会更新default缓存配置的stale值。
预渲染行为#
较短的缓存生命周期会改变缓存内容的交付位置:
revalidate为0,或expire小于 5 分钟:不参与预渲染,成为在请求时解析的“动态空洞”。stale小于 30 秒:不参与预渲染,因为预取会在用户点击之前过期。stale至少 30 秒但小于 5 分钟:参与预渲染,但不包含在路由的 App Shell 中。
在预设配置中,只有 seconds 落入上述任何阈值:其 1 分钟的 expire 使其不参与预渲染。
这种行为允许你在同一页面内混合静态和动态内容。静态部分会被预渲染,而短期缓存会创建边界,使数据在请求时而不是构建时获取。在动态缓存周围使用 <Suspense> 边界,以便在内容加载时提供回退内容。
示例#
使用预设配置#
配置缓存最简单的方法是使用预设配置。选择一个与内容更新模式相匹配的配置:
import { cacheLife } from 'next/cache'
export default async function BlogPost() {
'use cache'
cacheLife('days') // 博客文章每天更新
const post = await fetchBlogPost()
return <article>{post.content}</article>
}import { cacheLife } from 'next/cache'
export default async function ProductPage() {
'use cache'
cacheLife('hours') // 产品数据每天更新多次
const product = await fetchProduct()
return <div>{product.name}</div>
}满足特定需求的自定义配置#
当预设选项不符合你的需求时,定义自定义配置:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
cacheLife: {
editorial: {
stale: 600, // 10 分钟
revalidate: 3600, // 1 小时
expire: 86400, // 1 天
},
marketing: {
stale: 300, // 5 分钟
revalidate: 1800, // 30 分钟
expire: 43200, // 12 小时
},
},
}
export default nextConfig然后在整个应用中使用这些配置:
import { cacheLife } from 'next/cache'
export default async function EditorialPage() {
'use cache'
cacheLife('editorial')
// ...
}特殊情况下的内联配置#
当特定函数需要一次性缓存行为时,使用内联配置:
import { cacheLife } from 'next/cache'
import { getDb } from '@lib/db'
async function getLimitedOffer() {
'use cache'
cacheLife({
stale: 60, // 1 分钟
revalidate: 300, // 5 分钟
expire: 3600, // 1 小时
})
const offer = await getDb().offer.findFirst({
where: { type: 'limited' },
orderBy: { created_at: 'desc' },
})
return offer
}
export async function GET() {
const offer = await getLimitedOffer()
return Response.json(offer)
}缓存单个函数#
将缓存应用于工具函数以实现细粒度控制:
import { cacheLife } from 'next/cache'
export async function getSettings() {
'use cache'
cacheLife('max') // 设置很少变化
return await fetchSettings()
}import { cacheLife } from 'next/cache'
export async function getRealtimeStats() {
'use cache'
cacheLife('seconds') // 统计数据持续更新
return await fetchStats()
}嵌套缓存行为#
当你嵌套 use cache 指令时(一个缓存的函数或组件使用另一个缓存的函数或组件),外层缓存的行为取决于它是否具有显式的 cacheLife。
外层具有显式 cacheLife#
无论内层缓存的生命周期如何,外层缓存都使用自己的生命周期。当外层缓存命中时,它会返回包含所有嵌套数据的完整输出。显式的 cacheLife 始终优先,无论它比内层生命周期更长还是更短。
import { cacheLife } from 'next/cache'
import { Widget } from './widget'
export default async function Dashboard() {
'use cache'
cacheLife('hours') // 外层作用域设置自己的生命周期
return (
<div>
<h1>Dashboard</h1>
<Widget />
</div>
)
}外层没有显式 cacheLife#
如果在外层缓存中不调用 cacheLife,它会使用 default 配置(15 分钟重新验证)。生命周期较短的内层缓存可以缩短外层缓存的 default 生命周期。生命周期较长的内层缓存不能将其延长到默认值之外。
import { Widget } from './widget'
export default async function Dashboard() {
'use cache'
// 没有 cacheLife 调用 - 使用默认值(15 分钟)
// 如果 Widget 为 5 分钟 → Dashboard 变为 5 分钟
// 如果 Widget 为 1 小时 → Dashboard 保持 15 分钟
return (
<div>
<h1>Dashboard</h1>
<Widget />
</div>
)
}建议指定显式的 cacheLife。 有了显式的生命周期值,你可以检查缓存的函数或组件并立即了解其行为,而无需追踪嵌套缓存。没有显式的生命周期值,行为将取决于内层缓存的生命周期,从而更难推理。
嵌套的短期缓存#
如预渲染行为中所述,短期缓存(revalidate 为零或 expire 小于 5 分钟)会成为不参与预渲染的动态空洞。
当短期缓存嵌套在另一个没有显式 cacheLife 的 use cache 中时,外层缓存的生命周期会通过传播而悄无声息地变短。为防止这种意外配置错误,Next.js 会在预渲染期间抛出错误。
请注意,嵌套缓存可能并不明显——它可能位于导入的模块中,甚至是第三方依赖项中:
import { cacheLife } from 'next/cache'
export async function ShortLivedWidget() {
'use cache'
cacheLife('seconds')
const data = await fetchRealtimeData()
return <div>{data}</div>
}在另一个没有显式 cacheLife 的 use cache 中使用此组件将在预渲染期间报错:
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
// 错误:外层缓存没有显式的 cacheLife
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}要修复此错误,请为外层 use cache 添加显式的 cacheLife():
如果你希望外层缓存保持静态(预渲染),请设置更长的缓存生命周期:
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
export default async function Page() {
'use cache'
cacheLife('default') // 显式的 cacheLife 可防止此错误
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toISOString()}</p>
<ShortLivedWidget />
</div>
)
}如果你希望外层缓存也是短期的,请显式设置较短的缓存生命周期以确认这是有意为之。将组件包装在 <Suspense> 边界中,以便在内容加载时提供回退内容:
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'
async function Content() {
'use cache: remote'
cacheLife('seconds') // 显式的 cacheLife 确认这是有意的短期缓存
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>
)
}注意: 本示例使用
"use cache: remote",因为在无服务器部署中,使用默认的内存缓存时,运行时缓存无法跨请求持久保留。对于自托管环境,"use cache"可能就足够了。有关更多详细信息,请参阅运行时缓存注意事项。
条件缓存生命周期#
你可以在不同的代码路径中条件性地调用 cacheLife,以根据应用逻辑设置不同的缓存时长:
import { cacheLife, cacheTag } from 'next/cache'
async function getPostContent(slug: string) {
'use cache'
const post = await fetchPost(slug)
// 为缓存条目添加标签,以便进行定向重新验证
cacheTag(`post-${slug}`)
if (!post) {
// 内容可能尚未发布,或者可能处于草稿状态
// 短暂缓存以减少数据库负载
cacheLife('minutes')
return null
}
// 已发布的内容可以缓存更长时间
cacheLife('days')
// 只返回必要的数据,以保持缓存大小最小
return post.data
}当不同结果需要不同的缓存时长时,此模式很有用,例如,当某个条目缺失但很可能稍后可用时。
使用来自数据的动态缓存生命周期#
如果你想在运行时计算缓存生命周期,例如从获取的数据中读取,请使用内联缓存配置对象:
import { cacheLife, cacheTag } from 'next/cache'
async function getPostContent(slug: string) {
'use cache'
const post = await fetchPost(slug)
cacheTag(`post-${slug}`)
if (!post) {
cacheLife('minutes')
return null
}
// 直接使用 CMS 数据中的缓存时间作为对象
cacheLife({
// 确保 post.revalidateSeconds 是以秒为单位的数字
// stale 和 expire 继承自 'default' 配置
revalidate: post.revalidateSeconds ?? 3600,
})
return post.data
}版本历史#
| 版本 | 变更 |
|---|---|
v16.0.0 | cacheLife 已稳定。unstable_cacheLife 已弃用。 |
请参阅 Next.js 16 升级指南,将导入从 unstable_cacheLife 更新为 cacheLife。