use cache
了解如何使用 "use cache" 指令在 Next.js 应用中缓存数据。
use cache 指令允许你将路由、React 组件或函数标记为可缓存。它可以用在文件顶部,表示该文件中的所有导出都应被缓存;也可以内联在函数或组件顶部,以缓存返回值。使用 use cache 的函数和组件必须是异步的。
小知识:
- 要使用 cookies 或 headers,请在缓存作用域之外读取它们,并将值作为参数传递。这是首选模式。
- 如果内存缓存不足以满足运行时数据的需求,
'use cache: remote'允许平台提供专用的缓存处理器,但这需要一次网络往返来检查缓存,并且通常会产生平台费用。- 出于合规要求,或当你无法重构代码以将运行时数据作为参数传递给
use cache作用域时,请参阅'use cache: private'。
用法#
use cache 是 Cache Components 的一项功能。要启用它,请在 next.config.ts 文件中添加 cacheComponents 选项:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig然后,在函数、组件或文件级别添加 use cache。被缓存的函数和组件必须是异步的:
// 函数级别
export async function getData() {
'use cache'
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
// 组件级别
export async function MyComponent() {
'use cache'
return <></>
}在文件级别使用时,每个导出的函数都会成为缓存函数,并且也必须是异步的:
// 文件级别
'use cache'
export default async function Page() {
// ...
}use cache 如何工作#
缓存键#
缓存条目的键是使用其输入的序列化版本生成的,包括:
- Build ID —— 每次构建唯一,更改它会使所有缓存条目失效。如果配置了
deploymentId,它会覆盖 Build ID 作为缓存键的用途。 - Function ID —— 函数在代码库中位置和签名的安全哈希
- 可序列化的参数 —— Props(对于组件)或函数参数
- HMR refresh hash(仅开发环境)—— 在热模块替换时使缓存失效
当缓存函数引用外部作用域中的变量时,这些变量会被自动捕获并绑定为参数,从而成为缓存键的一部分。
async function Component({ userId }: { userId: string }) {
const getData = async (filter: string) => {
'use cache'
// 缓存键包含 userId(来自闭包)和 filter(参数)
const res = await fetch(
`https://api.example.com/users/${userId}/data?filter=${filter}`
)
return res.json()
}
return getData('active')
}在上面的代码片段中,userId 从外部作用域捕获,filter 作为参数传递,因此两者都成为 getData 函数缓存键的一部分。这意味着不同的用户和过滤器组合将拥有各自的缓存条目。
小知识: 当缓存函数读取root 参数时,只有它实际读取的参数才会成为其缓存键的一部分。
缓存输出#
缓存函数对于相同的输入会产生相同的输出。第一次使用给定输入集调用时会运行函数体并存储其输出。此后每次使用相同输入的调用都会复用该输出,无论是在同一次渲染过程中还是跨请求,只要该条目仍然有效。
输出由缓存处理器存储,默认存储在内存中,并一直保留到它们重新验证为止。
import { cacheLife } from 'next/cache'
export async function getOrderSummary(accountId: string) {
'use cache'
cacheLife('hours')
const orders = await getOrders(accountId)
const totals = await getOrderTotals(accountId)
return { orders, totals }
}
export async function getOrders(accountId: string) {
'use cache'
cacheLife('hours')
return db.orders.findMany({ where: { accountId } })
}
export async function getOrderTotals(accountId: string) {
return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } })
}在上面的示例中,每个 accountId 都有自己对应的 getOrderSummary 条目,保存其返回的序列化 { orders, totals } 对象。对 getOrders 的调用有各自的条目,以相同的 accountId 作为键。如果先前的调用(无论是通过 summary 还是直接调用)已经填充了某个条目,db.orders.findMany 就不会运行,这些订单数据也会成为 summary 输出的一部分。关于内部生命周期如何影响其外层条目,请参阅嵌套缓存行为。
请注意,getOrderTotals 没有被缓存。它被导出是为了让应用的其他部分可以在未缓存的作用域中读取最新的总计数据。不过,在 getOrderSummary 内部,只有在该函数按照那里设置的 'hours' 生命周期运行时,总计查询才会运行。
使用 Cache Components 时,预渲染会填充该条目并继续渲染,因此此输出会贡献到路由的静态外壳,并可能有助于其预取。如果缓存生命周期太短而无法安全存储,则会留下一个在请求时解析的空洞。有关阈值,请参阅预渲染行为。
序列化#
缓存函数的参数及其返回值必须是可序列化的。
有关完整参考,请参阅:
小知识: 参数和返回值使用不同的序列化系统。Server Component 的序列化(用于参数)比 Client Component 的序列化(用于返回值)更严格。这意味着你可以返回 JSX 元素,但不能将它们作为参数接受,除非使用透传模式。
支持的类型#
参数:
- 原始类型:
string、number、boolean、null、undefined - 普通对象:
{ key: value } - 数组:
[1, 2, 3] - Dates、Maps、Sets、TypedArrays、ArrayBuffers
- React 元素(仅作为透传)
返回值:
- 与参数相同,另外还包括 JSX 元素
不支持的类型#
- 类的实例
- 函数(作为透传的除外)
- Symbols、WeakMaps、WeakSets
- URL 实例
// 有效 —— 原始类型和普通对象
async function UserCard({
id,
config,
}: {
id: string
config: { theme: string }
}) {
'use cache'
return <div>{id}</div>
}
// 无效 —— 类的实例
async function UserProfile({ user }: { user: UserClass }) {
'use cache'
// 错误:无法序列化类的实例
return <div>{user.name}</div>
}透传(不可序列化的参数)#
只要不对不可序列化的值进行内省,你就可以接受它们。这支持使用 children 和 Server Actions 的组合模式:
async function CachedWrapper({ children }: { children: ReactNode }) {
'use cache'
// 不要读取或修改 children —— 直接透传
return (
<div className="wrapper">
<header>Cached Header</header>
{children}
</div>
)
}
// 用法:children 可以是动态的
export default function Page() {
return (
<CachedWrapper>
<DynamicComponent />
</CachedWrapper>
)
}你还可以通过缓存组件传递 Server Actions:
async function CachedForm({ action }: { action: () => Promise<void> }) {
'use cache'
// 不要在这里调用 action —— 直接透传
return <form action={action}></form>
}抛出的错误#
在缓存函数内部抛出的错误会跨越序列化边界,即使被服务端上的另一个函数捕获也是如此。调用方收到的是重建后的错误。自定义错误类以及诸如 code 或 status 之类的属性不会被保留,因此像 error instanceof CustomError 这样的检查会失败。
在开发环境中,错误会保留其原始的 name、message 和堆栈以供调试。在生产环境中,原始的名称和消息会被替换为通用错误,并包含一个 digest,用于将其与服务端日志中的原始错误关联起来。
对于预期的失败情况,请返回一个可序列化的值,例如 { ok: false, code: 'NOT_FOUND' },并在调用方根据返回值进行分支处理。
约束#
缓存函数在隔离的环境中执行。以下约束确保缓存行为保持可预测和安全。
请求时 API#
缓存函数和组件不能访问诸如 cookies()、headers() 或 searchParams 之类的运行时 API,并且该限制会沿调用栈传递:缓存函数调用的辅助函数如果读取其中任何一个,也会以同样的方式失败,并产生 next-request-in-use-cache 错误。在动态渲染的路由上,这会在路由运行时显现,因此它可能通过 next build,却在 next start 下失败。请在缓存作用域之外读取这些值,并将它们作为参数传递。
运行时缓存注意事项#
虽然 use cache 主要设计用于将未缓存的数据纳入静态外壳,但它也可以使用内存中的 LRU(最近最少使用)存储在运行时缓存数据。
使用默认的内存处理器时,运行时缓存行为取决于你的托管环境:
| 环境 | 运行时缓存行为 |
|---|---|
| Serverless | 缓存条目通常不会跨请求保留(每个请求可能是不同的实例),也不会在重新验证期间保留。构建时缓存正常工作。 |
| 自托管 | 缓存条目跨请求保留。使用 cacheMaxMemorySize 控制缓存大小。 |
例如,在 serverless 环境中,由两个页面共享的缓存函数会在每次静态外壳重新验证时执行,而在自托管或具有持久内存环境中,只要缓存输出仍然新鲜就会被复用。
关于跨服务端实例的标签失效,请参阅分布式标签协调。
托管服务提供商可以替换默认的缓存处理器,有些提供商不会在运行时存储 use cache 的输出。预渲染期间计算的值仍会被后续请求复用,但请求时计算的值则不会。请查阅托管服务提供商的文档以了解其运行时缓存行为。
如果默认的内存缓存不够用,或者你的提供商不存储运行时输出,请考虑使用 use cache: remote,它允许平台提供专用的缓存处理器(如 Redis 或 KV 数据库)。这有助于减少针对未按总流量扩展的数据源的访问,但也会带来成本(存储、网络延迟、平台费用)。
[!NOTE] 使用默认的内存处理器时,serverless 实例是短暂的,因此条目可能不会在请求之间复用,这与
use cache: remote不同。两种缓存指令都不会延续到新的部署,因为缓存键包含构建(或deploymentId)ID。对于需要跨部署持久保存的数据,请对非
fetch函数使用unstable_cache,或使用fetch缓存。
在极少数情况下,出于合规要求,或当你无法重构代码以将运行时数据作为参数传递给 use cache 作用域时,你可能需要 use cache: private。
Draft Mode(草稿模式)#
当 Draft Mode 启用时,所有缓存函数和组件都会在每个请求上重新执行,结果不会保存到缓存中。这确保草稿内容始终新鲜,而无需对你的缓存代码做任何更改。
你可以在 use cache 作用域内从 draftMode() 读取 isEnabled,但是,其他运行时 API(如 cookies() 和 headers())是不允许的,即使 Draft Mode 处于活动状态也是如此。有关推荐的模式,请参阅向缓存函数传递运行时值。
import { draftMode } from 'next/headers'
async function Content() {
'use cache'
const { isEnabled } = await draftMode()
const url = isEnabled
? 'https://draft.example.com/content'
: 'https://production.example.com/content'
const data = await fetch(url)
return <article></article>
}在缓存指令作用域内调用 enable() 或 disable() 也会抛出错误。Draft Mode 只能在 Route Handlers 或 Server Actions 中切换。
React.cache 隔离#
React.cache 在 use cache 边界内的隔离作用域中运行。在 use cache 函数之外通过 React.cache 存储的值在函数内部不可见。
这意味着你不能使用 React.cache 将数据传递到 use cache 作用域中:
import { cache } from 'react'
const store = cache(() => ({ current: null as string | null }))
function Parent() {
const shared = store()
shared.current = 'value from parent'
return <Child />
}
async function Child() {
'use cache'
const shared = store()
// shared.current 为 null,而不是 'value from parent'
// use cache 有自己隔离的 React.cache 作用域
return <div>{shared.current}</div>
}这种隔离确保缓存函数具有可预测、自包含的行为。要将数据传递到 use cache 作用域,请改用函数参数。
运行时的 use cache#
在服务端,缓存条目存储在内存中,并遵循 cacheLife 配置中的 revalidate 和 expire 时间。你可以通过在 next.config.js 文件中配置 cacheHandlers 来自定义缓存存储。
在客户端,来自服务端缓存的内容会在浏览器内存中存储 stale 时间所定义的时长。无论配置如何,客户端路由器都会强制执行最短 30 秒的 stale 时间。
x-nextjs-stale-time 响应头将缓存生命周期从服务端传达给客户端,以确保行为协调一致。
重新验证#
缓存函数会根据其 cacheLife 配置中的 revalidate 和 expire 时间进行重新验证,或通过标签按需重新验证。这两种方法并不互斥,通常会配合使用:
例如,一篇只有在作者编辑时才会变化的博客文章,可以使用较长的 cacheLife(如 max)并配合 cacheTag,然后在文章保存时按需使其失效。而一天中不断更新的最新文章列表,可以使用较短的配置(如 hours)来自行刷新,而无需手动失效。
基于时间的重新验证#
在每个 use cache 作用域中使用 cacheLife 设置明确的缓存生命周期。这使缓存行为在调用点清晰可见,而不是依赖于 default 配置或周围的缓存。
import { cacheLife } from 'next/cache'
async function getData() {
'use cache'
cacheLife('hours') // 使用内置的 'hours' 配置
const res = await fetch('https://api.example.com/data')
return res.json()
}如果省略 cacheLife,则会应用 default 配置,生命周期在调用点将不再明确:
- stale:5 分钟(客户端)
- revalidate:15 分钟(服务端)
- expire:永不因时间而过期
async function getData() {
'use cache'
// 隐式使用 'default' 配置
const res = await fetch('https://api.example.com/data')
return res.json()
}将一个生命周期较短的 use cache 嵌套在没有显式 cacheLife 的 use cache 中,会在预渲染期间导致构建失败。有关规则和修复方法,请参阅嵌套的短生命周期缓存。
按需重新验证#
使用 cacheTag、updateTag 或 revalidateTag 进行按需缓存失效:
import { cacheTag } from 'next/cache'
async function getProducts() {
'use cache'
cacheTag('products')
const res = await fetch('https://api.example.com/products')
return res.json()
}'use server'
import { updateTag } from 'next/cache'
export async function updateProduct() {
await db.products.update(...)
updateTag('products') // 使所有 'products' 缓存失效
}cacheLife 和 cacheTag 都跨越客户端和服务端缓存层进行集成,这意味着你只需在一个地方配置缓存语义,它们就会在所有地方生效。
示例#
使用 use cache 缓存函数输出#
你可以将 use cache 添加到任何异步函数中,而不仅仅是组件和路由。你可能希望缓存网络请求、数据库查询或耗时的计算。
export async function getData() {
'use cache'
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}export async function getData() {
'use cache'
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}Proxy 不会应用指令转换,因此 use cache 在 Proxy 中不起作用。当 Proxy 导入应用中其他地方已缓存的函数时,该函数会作为普通函数运行。
在该函数中调用 cacheLife 或 cacheTag 会抛出异常,因为 Proxy 不会创建缓存作用域。
使用 use cache 缓存组件输出#
你可以在组件级别使用 use cache 来缓存该组件内执行的任何数据获取或计算。只要序列化后的 props 在每个实例中产生相同的值,缓存条目就会被复用。
export async function Bookings({ type = 'haircut' }: BookingsProps) {
'use cache'
async function getBookingsData() {
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data
}
return //...
}
interface BookingsProps {
type: string
}export async function Bookings({ type = 'haircut' }) {
'use cache'
async function getBookingsData() {
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data
}
return //...
}交错使用#
在 React 中,使用 children 或插槽进行组合是构建灵活组件的众所周知模式。使用 use cache 时,你可以继续以这种方式组合 UI。返回的 JSX 中作为 children 或其他组合插槽包含的任何内容都会透传缓存组件,而不会影响其缓存条目。
只要你在可缓存函数体内不直接引用任何 JSX 插槽,它们出现在返回的输出中就不会影响缓存条目。
export default async function Page() {
const uncachedData = await getData()
return (
// 将组合插槽作为 props 传递,例如 header 和 children
<CacheComponent header={<h1>Home</h1>}>
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({
header, // header:一个组合插槽,作为 prop 注入
children, // children:另一个用于嵌套组合的插槽
}: {
header: ReactNode
children: ReactNode
}) {
'use cache'
const res = await fetch('https://api.example.com/cached-data')
const cachedData = await res.json()
return (
<div>
{header}
<PrerenderedComponent data={cachedData} />
{children}
</div>
)
}export default async function Page() {
const uncachedData = await getData()
return (
// 将组合插槽作为 props 传递,例如 header 和 children
<CacheComponent header={<h1>Home</h1>}>
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({
header, // header:一个组合插槽,作为 prop 注入
children, // children:另一个用于嵌套组合的插槽
}) {
'use cache'
const res = await fetch('https://api.example.com/cached-data')
const cachedData = await res.json()
return (
<div>
{header}
<PrerenderedComponent data={cachedData} />
{children}
</div>
)
}你还可以通过缓存组件将 Server Actions 传递给 Client Components,而无需在可缓存函数内部调用它们。
import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// 执行一些服务端更新操作
await db.update(...)
}
return <CachedComponent performUpdate={performUpdate} />
}
async function CachedComponent({
performUpdate,
}: {
performUpdate: () => Promise<void>
}) {
'use cache'
// 不要在这里调用 performUpdate
return <ClientComponent action={performUpdate} />
}import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// 执行一些服务端更新操作
await db.update(...)
}
return <CachedComponent performUpdate={performUpdate} />
}
async function CachedComponent({ performUpdate }) {
'use cache'
// 不要在这里调用 performUpdate
return <ClientComponent action={performUpdate} />
}'use client'
export default function ClientComponent({
action,
}: {
action: () => Promise<void>
}) {
return <button onClick={action}>Update</button>
}'use client'
export default function ClientComponent({ action }) {
return <button onClick={action}>Update</button>
}使用 use cache 缓存模块的导出#
将该指令放在文件顶部即可覆盖所有导出,而无需在每个导出上重复。它覆盖的每个导出函数都必须是异步的。
'use cache'
export async function getMonthlyTotals(accountId: string) {
return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } })
}
export async function getTopProducts() {
return db.products.findMany({ orderBy: { sales: 'desc' }, take: 10 })
}框架函数的导出也和其他导出一样被覆盖,因此在此类文件中 generateMetadata 和 generateStaticParams 必须是异步的。
小知识:
- 当某个缓存指令(
use cache、use cache: private或use cache: remote)位于文件顶部时,你可以将其导出的函数导入到 Client Component 中并直接调用;这些函数在服务端运行并返回结果,类似于 Server Function。更推荐的做法是在服务端调用缓存函数,并将结果作为 props 向下传递。- 只有导出的函数对 Client Components 可用。其他导出(如常量和对象)会被从客户端接收的内容中丢弃,因此导入它们会导致构建失败,并出现"export doesn't exist"错误。请将共享值移到没有该指令的单独文件中。
使用 use cache 缓存路由段的输出#
page 或 layout 文件也是一个模块,因此其中的文件级指令遵循相同的规则。每个路由段都是独立的入口点,并独立缓存。要预渲染整个路由,请在它渲染的每个段文件顶部添加 use cache:page、layout 以及任何并行路由插槽。
'use cache'
export default async function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}'use cache'
export default async function Layout({ children }) {
return <div>{children}</div>
}被缓存的 layout 不会缓存它渲染的 children,因为插槽会透传而不影响其缓存条目。请参阅交错使用。
'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// 遍历用户
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// 遍历用户
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}故障排除#
调试缓存行为#
详细日志#
设置 NEXT_PRIVATE_DEBUG_CACHE=1 以启用详细的缓存日志:
NEXT_PRIVATE_DEBUG_CACHE=1 npm run dev
# 或者用于生产环境
NEXT_PRIVATE_DEBUG_CACHE=1 npm run start小知识: 此环境变量还会记录 ISR 和其他缓存机制的日志。有关更多详细信息,请参阅验证正确的生产行为。
控制台日志重放#
在开发环境中,来自缓存函数的控制台日志会带有 Cache 前缀。
构建挂起(缓存超时)#
如果你的构建挂起,说明你正在访问在 use cache 边界之外创建的、解析为未缓存数据或运行时数据的 Promise。缓存函数会等待在构建期间无法解析的数据,从而在 50 秒后导致超时。
当构建超时时,你会看到以下错误消息:
错误:在预渲染期间填充缓存超时,很可能是因为请求特定的参数(如 params、searchParams、cookies() 或未缓存的数据)被用在 "use cache" 内部。
发生这种情况的常见方式包括:将此类 Promise 作为 props 传递、通过闭包访问它们,或从共享存储(Maps)中检索它们。
小知识: 在
use cache内部直接调用cookies()或headers()会立即失败,并产生不同的错误,而不是超时。
将运行时数据 Promise 作为 props 传递:
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
const cookieStore = cookies()
return <Cached promise={cookieStore} /> // 构建挂起
}
async function Cached({ promise }: { promise: Promise<unknown> }) {
'use cache'
const data = await promise // 在构建期间等待运行时数据
return <p>..</p>
}在 Dynamic 组件中 await cookies store,并将 cookie 值传递给 Cached 组件。
共享的去重存储:
// 问题:Map 存储了动态 Promise,并被缓存代码访问
import { Suspense } from 'react'
const cache = new Map<string, Promise<string>>()
export default function Page() {
return (
<>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic id="data" />
</Suspense>
<Cached id="data" />
</>
)
}
async function Dynamic({ id }: { id: string }) {
// 将动态 Promise 存储在共享 Map 中
cache.set(
id,
fetch(`https://api.example.com/${id}`).then((r) => r.text())
)
return <p>Dynamic</p>
}
async function Cached({ id }: { id: string }) {
'use cache'
return <p>{await cache.get(id)}</p> // 构建挂起 —— 检索到动态 Promise
}使用 Next.js 内置的 fetch() 去重功能,或为缓存和未缓存的上下文使用独立的 Maps。
平台支持#
| 部署选项 | 是否支持 |
|---|---|
| Node.js server | 是 |
| Docker container | 是 |
| Static export | 否 |
| Adapters | 取决于平台 |
了解在自托管 Next.js 时如何配置缓存。
版本历史#
| 版本 | 变更 |
|---|---|
v16.0.0 | "use cache" 已稳定,并随 Cache Components 功能一同启用。 |
v15.0.0 | "use cache" 作为实验性功能引入。 |