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 选项:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
然后,在函数、组件或文件层级添加 use cache。被缓存的函数和组件必须是异步的:
// Function level
export async function getData() {
'use cache'
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
// Component level
export async function MyComponent() {
'use cache'
return <></>
}
在文件层级使用时,每个导出的函数都会成为被缓存的函数,并且也必须是异步的:
// File level
'use cache'
export default async function Page() {
// ...
}
use cache 的工作原理
缓存键
缓存条目的键由其输入的序列化版本生成,包括:
- Build ID - 每次构建唯一,更改它会令所有缓存条目失效。如果配置了
deploymentId,则在计算缓存键时会覆盖 Build ID。 - Function ID - 函数在代码库中位置和签名的安全哈希
- 可序列化的参数 - Props(对于组件)或函数参数
- HMR 刷新哈希(仅开发环境)- 在热模块替换时使缓存失效
当被缓存的函数引用外部作用域中的变量时,这些变量会被自动捕获并绑定为参数,从而成为缓存键的一部分。
async function Component({ userId }: { userId: string }) {
const getData = async (filter: string) => {
'use cache'
// Cache key includes both userId (from closure) and filter (argument)
const res = await fetch(
`https://api.example.com/users/${userId}/data?filter=${filter}`
)
return res.json()
}
return getData('active')
}
在上面的代码片段中,userId 从外部作用域被捕获,filter 作为参数传入,因此两者都会成为 getData 函数缓存键的一部分。这意味着不同的 user 和 filter 组合会有各自的缓存条目。
补充说明:
当被缓存的函数读取根参数时,只有它实际读取的参数才会成为其缓存键的一部分。
缓存输出
缓存函数对相同输入会产生相同的输出。使用给定输入集合的第一次调用会执行函数体并存储其输出。之后每次使用相同输入的调用都会复用该输出,在一次渲染过程中以及跨请求均如此,只要该条目存在就一直有效。
输出由缓存处理器存储,默认存储在内存中,并持续到它们重新验证为止。
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' 生命周期运行时才执行。
使用 缓存组件 时,预渲染会填充该条目并继续渲染,因此此输出会贡献到路由的静态外壳,也可能贡献到其预取。缓存生命周期太短而无法安全存储时,会留下一个空洞,改为在请求时解析。有关阈值,请参阅预渲染行为。
序列化
缓存函数的参数及其返回值必须是可序列化的。
完整参考请参阅:
须知:
参数和返回值使用不同的序列化系统。服务器组件序列化(用于参数)比客户端组件序列化(用于返回值)限制更严格。这意味着你可以返回 JSX 元素,但除非使用透传模式,否则不能将它们作为参数接收。
支持的类型
参数:
- 原始类型:
string、number、boolean、null、undefined - 普通对象:
{ key: value } - 数组:
[1, 2, 3] - Dates、Maps、Sets、TypedArrays、ArrayBuffers
- React 元素(仅限透传)
返回值:
- 与参数相同,另外还包括 JSX 元素
不支持的类型
- 类实例
- 函数(透传时除外)
- Symbols、WeakMaps、WeakSets
- URL 实例
// Valid - primitives and plain objects
async function UserCard({
id,
config,
}: {
id: string
config: { theme: string }
}) {
'use cache'
return <div>{id}</div>
}
// Invalid - class instance
async function UserProfile({ user }: { user: UserClass }) {
'use cache'
// Error: Cannot serialize class instance
return <div>{user.name}</div>
}
透传(不可序列化的参数)
你可以接受不可序列化的值,只要不对它们进行内省。这支持与 children 和服务器操作的组合模式:
async function CachedWrapper({ children }: { children: ReactNode }) {
'use cache'
// Don't read or modify children - just pass it through
return (
<div className="wrapper">
<header>Cached Header</header>
{children}
</div>
)
}
// Usage: children can be dynamic
export default function Page() {
return (
<CachedWrapper>
<DynamicComponent /> {/* Not cached, passed through */}
</CachedWrapper>
)
}
你还可以通过缓存组件传递服务器操作:
async function CachedForm({ action }: { action: () => Promise<void> }) {
'use cache'
// Don't call action here - just pass it through
return <form action={action}>{/* ... */}</form>
}
约束
缓存函数在隔离环境中执行。以下约束可确保缓存行为保持可预测且安全。
请求时 API
缓存函数和组件不能访问诸如 cookies()、headers() 或 searchParams 的运行时 API,而且该限制会沿调用栈生效:缓存函数所调用的辅助函数如果读取其中任何一个,也会以相同方式失败,并出现 next-request-in-use-cache 错误。在动态渲染的路由中,这会在路由运行时暴露出来,因此它可能通过 next build,但在 next start 下失败。请在缓存作用域之外读取这些值,并将它们作为参数传入。
运行时缓存注意事项
虽然 use cache 的主要设计目标是将未缓存的数据包含到静态外壳中,但它也可以在运行时使用内存中的 LRU(最近最少使用)存储来缓存数据。
使用默认的内存处理器时,运行时缓存行为取决于你的托管环境:
| 环境 | 运行时缓存行为 |
|---|---|
| 无服务器 | 缓存条目通常不会跨请求持久存在(每个请求可能由不同的实例处理),在重新验证期间也不会持久存在。构建时缓存正常工作。 |
| 自托管 | 缓存条目会跨请求持久存在。可使用 cacheMaxMemorySize 控制缓存大小。 |
例如,在无服务器环境中,两个页面共享的缓存函数会在每次静态外壳重新验证时执行;而在自托管或具有持久内存的环境中,如果缓存输出仍然有效,则会被复用。
如需跨服务器实例进行标签失效,请参阅 分布式标签协调。
托管提供商可以替换默认缓存处理器,有些提供商不会在运行时存储 use cache 的输出。预渲染期间计算的值仍会被后续请求复用,但请求时计算的值则不会。请查看托管提供商的文档,了解其运行时缓存行为。
如果默认的内存缓存不够用,或者你的提供商不存储运行时输出,可以考虑 use cache: remote,它允许平台提供专用的缓存处理器(例如 Redis 或 KV 数据库)。这有助于减少对未按总流量扩展的数据源的访问,但也会带来成本(存储、网络延迟、平台费用)。
注意:
使用默认的内存处理器时,无服务器实例是短暂的,所以不同请求之间可能无法复用条目,这与
use cache: remote不同。两种缓存指令都不会延续到新的部署,因为缓存键包含构建(或deploymentId)ID。对于需要跨部署持久化的数据,请使用
unstable_cache(用于非fetch函数)或fetch缓存。
极少数情况下,出于合规要求,或当你无法重构代码将运行时数据作为参数传递给 use cache 作用域时,你可能需要 use cache: private。
草稿模式
启用草稿模式后,所有缓存函数和组件都会在每个请求时重新执行,结果不会保存到缓存中。这确保草稿内容始终是最新的,而无需对缓存代码做任何更改。
在 use cache 作用域内,你可以从 draftMode() 读取 isEnabled,但是,即使草稿模式处于激活状态,也不允许使用像 cookies() 和 headers() 这样的其他运行时 API。有关推荐模式,请参阅将运行时值传递给缓存函数。
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() 也会抛出错误。草稿模式只能在路由处理器或服务器操作中切换。
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 is null, not 'value from parent'
// use cache has its own isolated React.cache scope
return <div>{shared.current}</div>
}
这种隔离确保缓存函数具有可预测且自包含的行为。要将数据传入 use cache 作用域,请改用函数参数。
运行时的 use cache
在服务器上,缓存条目存储在内存中,并遵循你的 cacheLife 配置中的 revalidate 和 expire 时间。你可以在 next.config.js 文件中配置 cacheHandlers 来自定义缓存存储。
在客户端上,来自服务器缓存的内容会存储在浏览器内存中,持续时间由 stale 时间定义。无论配置如何,客户端路由器都会强制执行最短 30 秒的 stale time。
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') // Use built-in 'hours' profile
const res = await fetch('https://api.example.com/data')
return res.json()
}
如果省略 cacheLife,则会应用 default 配置,生命周期在调用处就不再明确:
- stale:5 分钟(客户端)
- revalidate:15 分钟(服务器端)
- expire:永不按时间过期
async function getData() {
'use cache'
// Implicitly uses the 'default' profile
const res = await fetch('https://api.example.com/data')
return res.json()
}
在没有显式 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') // Invalidates all 'products' caches
}
cacheLife 和 cacheTag 都跨越客户端和服务器缓存层进行集成,这意味着你只需在一个地方配置缓存语义,它们就会在所有地方生效。
示例
使用 use cache 缓存函数输出
你可以将 use cache 添加到任何异步函数,而不仅限于组件和路由。你可能希望缓存网络请求、数据库查询或缓慢的计算。
TypeScript
export async function getData() {
'use cache'
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
JavaScript
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 在每个实例中产生相同的值,缓存条目就会被复用。
TypeScript
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
}
JavaScript
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 插槽,它们在返回输出中的存在就不会影响缓存条目。
TypeScript
export default async function Page() {
const uncachedData = await getData()
return (
// Pass compositional slots as props, e.g. header and children
<CacheComponent header={<h1>Home</h1>}>
{/* DynamicComponent is provided as the children slot */}
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({
header, // header: a compositional slot, injected as a prop
children, // children: another slot for nested composition
}: {
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>
)
}
JavaScript
export default async function Page() {
const uncachedData = await getData()
return (
// Pass compositional slots as props, e.g. header and children
<CacheComponent header={<h1>Home</h1>}>
{/* DynamicComponent is provided as the children slot */}
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({
header, // header: a compositional slot, injected as a prop
children, // children: another slot for nested composition
}) {
'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>
)
}
你还可以将服务器操作经缓存的组件传递给客户端组件,而无需在可缓存函数内调用它们。
TypeScript
import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// Perform some server-side update
await db.update(...)
}
return <CachedComponent performUpdate={performUpdate} />
}
async function CachedComponent({
performUpdate,
}: {
performUpdate: () => Promise<void>
}) {
'use cache'
// Do not call performUpdate here
return <ClientComponent action={performUpdate} />
}
'use client'
export default function ClientComponent({
action,
}: {
action: () => Promise<void>
}) {
return <button onClick={action}>Update</button>
}
JavaScript
import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// Perform some server-side update
await db.update(...)
}
return <CachedComponent performUpdate={performUpdate} />
}
async function CachedComponent({ performUpdate }) {
'use cache'
// Do not call performUpdate here
return <ClientComponent action={performUpdate} />
}
'use client'
export default function ClientComponent({ action }) {
return <button onClick={action}>Update</button>
}
使用 use cache 缓存模块的导出
将指令放在文件顶部即可覆盖所有导出,无需在每个导出上重复添加。它所覆盖的每个导出函数都必须是 async。
'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 必须是 async。
须知:
- 当缓存指令(
use cache、use cache: private或use cache: remote)位于文件顶部时,你可以将其导出函数导入到客户端组件中并直接调用;它们会在服务器上运行并返回结果,类似于服务器函数。建议在服务器上调用缓存函数,并将结果作为 props 向下传递。- 只有导出的函数可供客户端组件使用。其他导出(例如常量和对象)会从客户端接收的内容中被移除,因此导入它们会导致构建失败,并报 "export doesn't exist" 错误。请将共享值移到不带该指令的单独文件中。
使用 use cache 缓存路由段的输出
page 或 layout 文件也是一个模块,因此其中的文件级指令遵循相同的规则。每个路由段都是独立的入口点,并独立进行缓存。要预渲染整个路由,请在其渲染的每个段文件顶部添加 use cache:page、layout 以及任何并行路由插槽。
TypeScript
'use cache'
export default async function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
JavaScript
'use cache'
export default async function Layout({ children }) {
return <div>{children}</div>
}
缓存后的 layout 不会缓存它所渲染的 children,因为插槽会直接透传,不影响其入口。参见交错。
TypeScript
'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// loop through users
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}
JavaScript
'use cache'
async function Users() {
const res = await fetch('https://api.example.com/users')
const users = await res.json()
// loop through users
}
export default async function Page() {
return (
<main>
<Users />
</main>
)
}
故障排查
调试缓存行为
详细日志
设置 NEXT_PRIVATE_DEBUG_CACHE=1 以启用详细的缓存日志:
NEXT_PRIVATE_DEBUG_CACHE=1 npm run dev
# or for production
NEXT_PRIVATE_DEBUG_CACHE=1 npm run start
须知:
此环境变量还会记录 ISR 和其他缓存机制。更多详情请参见验证正确的生产环境行为。
控制台日志重放
在开发环境中,来自缓存函数的控制台日志会带有 Cache 前缀。
构建挂起(缓存超时)
如果构建挂起,说明你访问的 Promise 会解析为未缓存的数据或运行时数据,且这些 Promise 创建于 use cache 边界之外。缓存函数会等待在构建期间无法解析的数据,从而在 50 秒后超时。
当构建超时时,你会看到这条错误信息:
错误:预渲染期间填充缓存超时,可能是因为在 "use cache" 中使用了特定于请求的参数,例如 params、searchParams、cookies() 或未缓存的数据。
常见的发生方式:将此类 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} /> // Build hangs
}
async function Cached({ promise }: { promise: Promise<unknown> }) {
'use cache'
const data = await promise // Waits for runtime data during build
return <p>..</p>
}
在 Dynamic 组件中 await cookies store,并将 cookie 值传给 Cached 组件。
共享去重存储:
// Problem: Map stores dynamic Promises, accessed by cached code
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 }) {
// Stores dynamic Promise in shared 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> // Build hangs - retrieves dynamic Promise
}
使用 Next.js 内置的 fetch() 去重,或者为缓存和未缓存的上下文使用单独的 Map。
平台支持
| 部署选项 | 是否支持 |
|---|---|
| Node.js 服务器 | 是 |
| Docker 容器 | 是 |
| 静态导出 | 否 |
| 适配器 | 因平台而异 |
了解在自行托管 Next.js 时如何配置缓存。
版本历史
| 版本 | 变更 |
|---|---|
v16.0.0 |
"use cache" 已稳定,并通过 Cache Components 功能启用。 |
v15.0.0 |
"use cache" 作为实验性功能引入。 |
相关
查看相关 API 参考。
- use cache: private:了解如何使用 "use cache: private" 指令来缓存访问运行时请求 API 的函数。
- cacheComponents:了解如何在 Next.js 中启用 cacheComponents 标志。
- cacheLife:了解如何在 Next.js 中设置 cacheLife 配置。
- cacheHandlers:为 Next.js 中的 use cache 指令配置自定义缓存处理器。
- cacheTag:了解如何使用 cacheTag 函数在 Next.js 应用中管理缓存失效。
- cacheLife:了解如何使用 cacheLife 函数为已缓存的函数或组件设置缓存过期时间。
- revalidateTag:revalidateTag 函数的 API 参考。