Skip to content

'使用缓存:private'

¥'use cache: private'

'use cache: private' 指令允许函数在缓存作用域内访问运行时请求 API,例如 cookies()headers()searchParams。但是,结果永远不会存储在服务器上,它们仅缓存在浏览器内存中,并且不会在页面重新加载后保留。

¥The 'use cache: private' directive allows functions to access runtime request APIs like cookies(), headers(), and searchParams within a cached scope. However, results are never stored on the server, they're cached only in the browser's memory and do not persist across page reloads.

请求 'use cache: private' 的情况:

¥Reach for 'use cache: private' when:

由于此指令访问运行时数据,因此该函数会在每次服务器渲染时执行,并且不会在 静态 shell 生成期间运行。

¥Because this directive accesses runtime data, the function executes on every server render and is excluded from running during static shell generation.

无法为 'use cache: private' 配置自定义缓存处理程序。

¥It is not possible to configure custom cache handlers for 'use cache: private'.

有关不同缓存指令的比较,请参阅 use cache: remoteuse cacheuse cache: private 的区别

¥For a comparison of the different cache directives, see How use cache: remote differs from use cache and use cache: private.

需要了解:此指令标记为 experimental,因为它依赖于运行时预取,而运行时预取目前尚不稳定。运行时预取是一项即将推出的功能,它允许路由将数据预取到 静态 shell 之后的任何缓存作用域,而不仅仅是私有缓存。

¥Good to know: This directive is marked as experimental because it depends on runtime prefetching, which is not yet stable. Runtime prefetching is an upcoming feature that will let the router prefetch past the static shell into any cached scope, not just private caches.

用法

¥Usage

要使用 'use cache: private',请在 next.config.ts 文件中启用 cacheComponents 标志:

¥To use 'use cache: private', enable the cacheComponents flag in your next.config.ts file:

tsx
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

然后将 'use cache: private' 添加到你的函数中,并添加 cacheLife 配置。

¥Then add 'use cache: private' to your function along with a cacheLife configuration.

需要了解:此指令在路由处理程序中不可用。

¥Good to know: This directive is not available in Route Handlers.

基本示例

¥Basic example

在本例中,我们演示了如何在 'use cache: private' 作用域内访问 cookie:

¥In this example, we demonstrate that you can access cookies within a 'use cache: private' scope:

tsx
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)
}

需要了解:要使运行时预取生效,stale 时间必须至少为 30 秒。详情请参阅 cacheLife 客户端路由缓存行为

¥Good to know: The stale time must be at least 30 seconds for runtime prefetching to work. See cacheLife client router cache behavior for details.

私有缓存中允许的请求 API

¥Request APIs allowed in private caches

以下请求特定的 API 可在 'use cache: private' 函数中使用:

¥The following request-specific APIs can be used inside 'use cache: private' functions:

APIuse cache 中允许'use cache: private' 中允许
cookies()
headers()
searchParams
connection()

注意:use cache'use cache: private' 均禁止使用 connection() API,因为它提供了无法安全缓存的连接特定信息。

¥Note: The connection() API is prohibited in both use cache and 'use cache: private' as it provides connection-specific information that cannot be safely cached.

版本历史

¥Version History

版本更改
v16.0.0"use cache: private" 通过缓存组件功能启用。