NNext.js 中文网 GitHub

use cache: private

了解如何使用 "use cache: private" 指令来缓存访问运行时请求 API 的函数。

'use cache: private' 指令允许函数在缓存作用域内访问运行时请求 API,如 cookies()、headers() 和 searchParams。在生产环境中,同一请求内匹配的调用可以复用相同的结果,但 Next.js 不会将其存储在跨请求的服务器缓存中。在开发环境中,Next.js 会将其存储在内存中,以请求的 cookie 和标头作为键,并将其提供给下一个匹配的请求,同时在后台生成新的结果。

客户端路由器可以使用 cacheLife 配置的 stale 时间将渲染输出保留在浏览器内存中。此客户端缓存不会在页面重新加载后持久保留。

在以下情况下使用 'use cache: private':

私有 Cache Functions 在请求时运行,并且不参与 static shell 的生成。要在组件需要其结果之前启动私有 Cache Function,请参阅预加载数据。

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

有关不同缓存指令的比较,请参阅 use cache: remote 与 use cache 和 use cache: private 的区别。

用法#

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

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  cacheComponents: true,
}

module.exports = nextConfig

然后在函数中添加 'use cache: private' 以及 cacheLife 配置。

基本示例#

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

app/product/[id]/page.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 })

  // 在私有缓存函数中访问 cookie
  const sessionId = (await cookies()).get('session-id')?.value || 'guest'

  return getPersonalizedRecommendations(productId, sessionId)
}
app/product/[id]/page.js
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 })

  // 在私有缓存函数中访问 cookie
  const sessionId = (await cookies()).get('session-id')?.value || 'guest'

  return getPersonalizedRecommendations(productId, sessionId)
}

小知识: stale 时间必须至少为 30 秒,按链接预取才能工作;必须至少为 5 分钟,内容才能包含在路由的 App Shell 中。有关详细信息,请参阅 cacheLife 预渲染行为。

配置客户端 stale 时间#

私有 Cache Functions 会将其 stale 时间贡献给路由的客户端缓存。如果某个函数只需要请求范围内的去重,请使用 cacheLife({ stale: Infinity }),以免降低路由的 stale 时间。

Next.js 使用路由缓存条目中最短的 stale 时间,因此其他缓存或路由设置仍可能设置一个有限值。将 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随 Cache Components 功能启用 "use cache: private"。
Next.js 中文网