use cache: private
了解如何使用“use cache: private”指令缓存访问运行时请求 API 的函数。
'use cache: private' 指令允许函数在缓存作用域内访问运行时请求 API,例如 cookies()、headers() 和 searchParams。在生产环境中,同一请求内的匹配调用可以复用相同结果,但 Next.js 不会将其存储在跨请求的服务器缓存中。在开发环境中,Next.js 会将其存储在内存中,以请求的 Cookie 和请求头作为键,并在后台生成新结果的同时将其提供给下一个匹配请求。
客户端路由可以将渲染输出保留在浏览器内存中,时长由 cacheLife 配置的 stale 时间 决定。此客户端缓存不会在页面重新加载后保留。
在以下情况下使用 'use cache: private':
- 你希望缓存一个已经访问运行时数据的函数,而通过将运行时访问移到外部并将值作为参数传递进行重构并不实际。
- 你需要将请求特定的数据排除在跨生产请求持久存在的服务器缓存之外。
私有缓存函数在请求时运行,并被排除在静态外壳生成之外。若要在组件需要其结果之前启动私有缓存函数,请参阅预加载数据。
不能为 'use cache: private' 配置自定义缓存处理器。
有关不同缓存指令的比较,请参阅use cache: remote 与 use cache 和 use cache: private 有何不同。
用法
要使用 'use cache: private',请在 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: private' 添加到函数中,并添加 cacheLife 配置。
基本示例
在此示例中,我们演示了可以在 'use cache: private' 作用域内访问 Cookie:
TypeScript
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }]
}
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading recommendations...</div>}>
<Recommendations productId={id} />
</Suspense>
</div>
)
}
async function Recommendations({ productId }: { productId: string }) {
const recommendations = await getRecommendations(productId)
return (
<div>
{recommendations.map((rec) => (
<ProductCard key={rec.id} product={rec} />
))}
</div>
)
}
async function getRecommendations(productId: string) {
'use cache: private'
cacheTag(`recommendations-${productId}`)
cacheLife({ stale: 60 })
// Access cookies within private cache functions
const sessionId = (await cookies()).get('session-id')?.value || 'guest'
return getPersonalizedRecommendations(productId, sessionId)
}
JavaScript
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }]
}
export default async function ProductPage({ params }) {
const { id } = await params
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading recommendations...</div>}>
<Recommendations productId={id} />
</Suspense>
</div>
)
}
async function Recommendations({ productId }) {
const recommendations = await getRecommendations(productId)
return (
<div>
{recommendations.map((rec) => (
<ProductCard key={rec.id} product={rec} />
))}
</div>
)
}
async function getRecommendations(productId) {
'use cache: private'
cacheTag(`recommendations-${productId}`)
cacheLife({ stale: 60 })
// Access cookies within private cache functions
const sessionId = (await cookies()).get('session-id')?.value || 'guest'
return getPersonalizedRecommendations(productId, sessionId)
}
须知:
stale时间必须至少为 30 秒,按链接预取才能生效;并且必须至少为 5 分钟,内容才会包含在路由的 App Shell 中。详情请参阅cacheLife预渲染行为。
配置客户端陈旧时间
私有缓存函数会将其 stale 时间计入路由的客户端缓存。如果函数只需要请求作用域内的去重,请使用 cacheLife({ stale: Infinity }) 以防止它降低路由的陈旧时间。
Next.js 使用路由缓存条目中最短的陈旧时间,因此其他缓存或路由设置仍可设置一个有限值。将 stale 设置为 Infinity 不会在生产请求之间将私有结果存储到服务器上。当客户端路由应在已知间隔后重新验证个性化输出时,请使用有限值。
私有缓存中允许使用的请求 API
以下特定于请求的 API 可以在 'use cache: private' 函数内使用:
| API | 允许在 use cache 中使用 |
允许在 'use cache: private' 中使用 |
|---|---|---|
cookies() |
否 | 是 |
headers() |
否 | 是 |
searchParams |
否 | 是 |
connection() |
否 | 否 |
注意:
connection()API 在use cache和'use cache: private'中均被禁止使用,因为它提供了无法安全缓存的连接特定信息。
版本历史
| 版本 | 变更 |
|---|---|
v16.0.0 |
"use cache: private" 在启用 Cache Components 功能后可用。 |
相关
查看相关 API 参考。
- use cache:了解如何使用 "use cache" 指令在 Next.js 应用中缓存数据。
- cacheComponents:了解如何在 Next.js 中启用 cacheComponents 标志。
- cacheLife:了解如何使用 cacheLife 函数为缓存的函数或组件设置缓存过期时间。
- cacheTag:了解如何使用 cacheTag 函数在 Next.js 应用中管理缓存失效。