N Next.js 中文
原文 ↗

cacheLife

了解如何使用 cacheLife 函数为已缓存的函数或组件设置缓存过期时间。

更新于 2026-11-18Next.js 16.4.6

cacheLife 函数用于设置函数或组件的缓存生命周期。它应与 use cache 指令配合使用,并且要位于该函数或组件的作用域内。

用法

基本设置

要使用 cacheLife,请首先启用 cacheComponents 标志(在您的 next.config.js 文件中):

TypeScript

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

JavaScript

next.config.jsjs
const nextConfig = {
  cacheComponents: true,
}

module.exports = nextConfig

cacheLife 只能在缓存指令作用域内使用。

在文件级别或异步函数/组件的顶部添加缓存指令(例如 use cache)。

cacheLife 不能在模块作用域中使用。在文件顶层调用它会抛出错误。

须知:

  • 我们建议在每个 use cache 作用域中设置 cacheLife,以便在调用处明确其行为。省略它会使生命周期变为隐式(将应用 default 配置档),从而更难推理,例如在嵌套缓存作用域中。
  • 在定义缓存的同一函数或组件中调用 cacheLife。避免将其抽象到共享工具中,以便缓存行为保持明确且易于推理。
  • 如果调用 cacheLife,请确保每次函数调用只执行一次调用。你可以在不同的控制流分支中调用它,但每个请求只应运行一个。请参阅条件缓存生命周期示例。

使用预设配置档

Next.js 提供覆盖常见缓存需求的预设缓存配置档。每个配置档平衡三个因素:

  • 用户在未检查更新的情况下看到缓存内容的时长(客户端)
  • 服务器生成新内容的频率
  • 旧内容完全过期的时间

根据内容变化的频率选择配置档:

  • seconds - 实时数据(股票价格、实时比分)
  • minutes - 频繁更新(社交信息流、新闻)
  • hours - 每日多次更新(商品库存、天气)
  • days - 每日更新(博客帖子、文章)
  • weeks - 每周更新(播客、新闻通讯)
  • max - 很少变更(法律页面、归档内容)

导入 cacheLife 并传入配置文件名:

app/blog/page.tsxtsx
'use cache'
import { cacheLife } from 'next/cache'

export default async function BlogPage() {
  cacheLife('days') // Blog content updated daily

  const posts = await getBlogPosts()
  return <div>{/* render posts */}</div>
}

配置文件名告诉 Next.js 如何缓存整个函数的输出。如果你不调用 cacheLife,则使用 default 配置文件。有关时序细节,请参阅预设缓存配置文件。

参考

缓存配置文件属性

缓存配置文件通过三个时序属性控制缓存行为:

  • stale:客户端在不检查服务器的情况下可以使用缓存数据的时长
  • revalidate:超过此时间后,下一次请求将触发后台刷新
  • expire:在此时间内没有请求后,下一次请求将等待获取最新内容

stale

客户端: 客户端在不检查服务器的情况下可以使用缓存数据的时长。

在此期间,客户端路由器会立即显示缓存内容,而无需任何网络请求。此时间过后,路由器在下一次导航或请求时必须向服务器确认。这样可以实现从客户端缓存即时加载页面,但数据可能已过时。

  • 如果省略,默认使用 default 配置文件的 stale 值(5 分钟,请参阅staleTimes)
  • 还决定该内容是否可以成为路由的 App Shell 的一部分。请参阅预渲染行为。
cacheLife({ stale: 300 }) // 5 minutes

revalidate

服务器在后台重新生成缓存内容的频率。

  • 如果在此时间段之后收到请求,服务器会:
    1. 立即提供缓存版本(如果可用)
    2. 在后台重新生成内容
    3. 用最新内容更新缓存
  • 类似于增量静态再生(ISR)
  • 如果省略,默认使用 default 配置文件的 revalidate 值(15 分钟)
cacheLife({ revalidate: 900 }) // 15 minutes

expire

服务器必须重新生成缓存内容之前的最长时间。

  • 在此时间段内无流量后,服务器将在下一次请求时同步重新生成内容
  • 当你同时设置 revalidate 和 expire 时,expire 必须大于 revalidate。Next.js 会对此进行校验,并在配置无效时抛出错误。
  • 如果省略,则默认为 default 配置档的 expire 值(永不过期)
cacheLife({ expire: 3600 }) // 1 hour

预设缓存配置档

如果你未指定配置档,Next.js 会使用 default 配置档。我们建议显式设置配置档,以使缓存行为更清晰。

配置档 使用场景 stale revalidate expire
default 标准内容 5 分钟 15 分钟 永不
seconds 实时数据 30 秒 1 秒 1 分钟
minutes 频繁更新的内容 5 分钟 1 分钟 1 小时
hours 每天更新多次的内容 5 分钟 1 小时 1 天
days 每天更新的内容 5 分钟 1 天 1 周
weeks 内容每周更新 5 分钟 1 周 30 天
max 很少变化的稳定内容 5 分钟 30 天 1 年

覆盖默认缓存配置

预设配置文件对应常见的时间段(seconds、minutes、hours、days、weeks),以及 default 和 max。你可以直接使用它们,也可以在 next.config.ts 中重新定义其中任意一个,包括 default 和 max。内置名称在编辑器自动补全中仍然可用。

重新定义内置配置是受支持的做法,但请在项目中记录说明,使像 cacheLife('hours') 这样的调用反映你设置的值,而不是预设值。以时间命名的配置带有直观的预期(days 大致读作 24 小时),因此重新定义它们比重新定义 default 或 max 更容易让读者感到意外,因为后两者并不暗示具体时长。同样可行的做法是定义你自己的自定义配置,而不是重载内置名称。

重新定义 default 还会改变 use cache 作用域未调用任何 cacheLife 时所应用的生存期。下面的示例将 default 设置为重新验证 1 小时:

next.config.tsts
const nextConfig = {
  cacheComponents: true,
  cacheLife: {
    // Redefine the 'default' profile
    default: {
      stale: 300, // 5 minutes
      revalidate: 3600, // 1 hour
      expire: 86400, // 1 day
    },
  },
}

export default nextConfig

须知:

cacheLife 函数的类型签名会在 next dev、next build 或 next typegen 期间根据 next.config.ts 生成,因此被覆盖配置的编辑器自动补全和 JSDoc 提示会反映你设置的值,而不是预设值。

自定义缓存配置

在 next.config.ts 中使用你自己的名称定义可复用的缓存配置:

TypeScript

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

const nextConfig: NextConfig = {
  cacheComponents: true,
  cacheLife: {
    biweekly: {
      stale: 60 * 60 * 24 * 14, // 14 days
      revalidate: 60 * 60 * 24, // 1 day
      expire: 60 * 60 * 24 * 14, // 14 days
    },
  },
}

export default nextConfig

JavaScript

next.config.jsjs
const nextConfig = {
  cacheComponents: true,
  cacheLife: {
    biweekly: {
      stale: 60 * 60 * 24 * 14, // 14 days
      revalidate: 60 * 60 * 24, // 1 day
      expire: 60 * 60 * 24 * 14, // 14 days
    },
  },
}

module.exports = nextConfig

上面的示例会缓存 14 天,每天检查更新,并在 14 天后使缓存过期。之后你可以在应用程序中按名称引用此配置:

须知:

自定义配置中任何省略的属性都会从 default 配置继承。这同样适用于直接传给 cacheLife() 的内联配置对象。

app/page.tsxtsx
'use cache'
import { cacheLife } from 'next/cache'

export default async function Page() {
  cacheLife('biweekly')
  return <div>Page</div>
}

内联缓存配置

对于一次性场景,可以直接将配置对象传给 cacheLife:

app/page.tsxtsx
'use cache'
import { cacheLife } from 'next/cache'

export default async function Page() {
  cacheLife({
    stale: 3600,
    revalidate: 900,
    expire: 86400,
  })

  return <div>Page</div>
}

内联配置仅适用于特定的函数或组件。对于可复用的配置,请在 next.config.ts 中定义自定义配置。

将 cacheLife({}) 与空对象一起使用会应用 default 配置的值。

客户端缓存行为

stale 属性控制的是客户端缓存,而不是 Cache-Control 响应头:

  • 服务器通过 x-nextjs-stale-time 响应头发送过期时间
  • 客户端路由器使用该值来确定何时重新验证
  • 强制要求至少 30 秒,以确保预取的链接保持可用

这一 30 秒的最短时限可防止预取数据在用户点击链接之前过期。它仅适用于基于时间的过期机制。

从服务器操作调用重新验证函数,可以在达到 stale 时间之前清除客户端缓存条目:

  • 当缓存配置解析为 expire: 0(包括内联 { expire: 0 })时,revalidatePath、updateTag 和 revalidateTag 会清除预取的路由以及为后退/前进导航保留的页面。
  • refresh 会清除为后退/前进导航保留的页面,并保留其他预取的路由。
  • revalidateTag 搭配解析为非零 expire 值(例如 'max')的缓存配置时,不会更改客户端缓存。

须知:

cacheLife 中的 stale 属性与 staleTimes 不同。staleTimes 是影响所有路由的全局设置,而 cacheLife 允许按函数或按路由进行配置。更新 staleTimes.static 也会更新 default 缓存配置的 stale 值。

预渲染行为

较短的缓存生命周期会改变缓存内容的交付来源:

  • 0 的 revalidate,或小于 5 分钟的 expire:会被排除在预渲染之外,成为在请求时解析的“动态空洞”。
  • stale 小于 30 秒:会被排除在预渲染之外,因为预取会在用户点击之前过期。
  • stale 至少为 30 秒但小于 5 分钟:会包含在预渲染中,但会被排除在路由的 App Shell 之外。

在这些预设中,只有 seconds 会落入上述任一阈值范围:其 1 分钟的 expire 会将它排除在预渲染之外。

这种行为允许你在同一页面中混合静态内容和动态内容。静态部分会被预渲染,而短生命周期的缓存会形成边界,使数据在请求时而非构建时获取。可在动态缓存周围使用 <Suspense> 边界,以便在内容加载期间提供回退内容。

示例

使用预设配置

配置缓存最简单的方式是使用预设配置。选择与你的内容更新模式相匹配的一个:

app/blog/[slug]/page.tsxtsx
import { cacheLife } from 'next/cache'

export default async function BlogPost() {
  'use cache'
  cacheLife('days') // Blog posts updated daily

  const post = await fetchBlogPost()
  return <article>{post.content}</article>
}
app/products/[id]/page.tsxtsx
import { cacheLife } from 'next/cache'

export default async function ProductPage() {
  'use cache'
  cacheLife('hours') // Product data updated multiple times per day

  const product = await fetchProduct()
  return <div>{product.name}</div>
}

针对特定需求的自定义配置

当预设选项不满足你的需求时,请定义自定义配置:

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

const nextConfig: NextConfig = {
  cacheComponents: true,
  cacheLife: {
    editorial: {
      stale: 600, // 10 minutes
      revalidate: 3600, // 1 hour
      expire: 86400, // 1 day
    },
    marketing: {
      stale: 300, // 5 minutes
      revalidate: 1800, // 30 minutes
      expire: 43200, // 12 hours
    },
  },
}

export default nextConfig

然后在你的整个应用中使用这些配置:

app/editorial/page.tsxtsx
import { cacheLife } from 'next/cache'

export default async function EditorialPage() {
  'use cache'
  cacheLife('editorial')
  // ...
}

用于特殊场景的内联配置

当某个特定函数需要一次性的缓存行为时,请使用内联配置:

app/api/limited-offer/route.tstsx
import { cacheLife } from 'next/cache'
import { getDb } from '@lib/db'

async function getLimitedOffer() {
  'use cache'

  cacheLife({
    stale: 60, // 1 minute
    revalidate: 300, // 5 minutes
    expire: 3600, // 1 hour
  })

  const offer = await getDb().offer.findFirst({
    where: { type: 'limited' },
    orderBy: { created_at: 'desc' },
  })

  return offer
}

export async function GET() {
  const offer = await getLimitedOffer()

  return Response.json(offer)
}

为单个函数添加缓存

对工具函数应用缓存以实现更细粒度的控制:

lib/api.tstsx
import { cacheLife } from 'next/cache'

export async function getSettings() {
  'use cache'
  cacheLife('max') // Settings rarely change

  return await fetchSettings()
}
lib/stats.tstsx
import { cacheLife } from 'next/cache'

export async function getRealtimeStats() {
  'use cache'
  cacheLife('seconds') // Stats update constantly

  return await fetchStats()
}

嵌套缓存行为

当你嵌套 use cache 指令时(一个已缓存的函数或组件使用另一个已缓存的函数或组件),外层缓存的行为取决于它是否具有显式的 cacheLife。

外层显式指定 cacheLife 时

外层缓存使用自己的生命周期,与内层缓存的生命周期无关。当外层缓存命中时,它返回包含所有嵌套数据的完整输出。无论比内层生命周期更长还是更短,显式的 cacheLife 始终优先。

app/dashboard/page.tsxtsx
import { cacheLife } from 'next/cache'
import { Widget } from './widget'

export default async function Dashboard() {
  'use cache'
  cacheLife('hours') // Outer scope sets its own lifetime

  return (
    <div>
      <h1>Dashboard</h1>
      <Widget /> {/* Inner scope has 'minutes' lifetime */}
    </div>
  )
}

外层未显式指定 cacheLife 时

如果你在外层缓存中没有调用 cacheLife,它将使用 default 配置(15 分钟重新验证)。生命周期较短的内层缓存可以缩短外层缓存的 default 生命周期。生命周期较长的内层缓存则无法将其延长到超过默认值。

app/dashboard/page.tsxtsx
import { Widget } from './widget'

export default async function Dashboard() {
  'use cache'
  // No cacheLife call - uses default (15 min)
  // If Widget has 5 min → Dashboard becomes 5 min
  // If Widget has 1 hour → Dashboard stays 15 min

  return (
    <div>
      <h1>Dashboard</h1>
      <Widget />
    </div>
  )
}

建议显式指定 cacheLife。 有了显式的生命周期值,你可以检查某个已缓存的函数或组件并立即知道它的行为,而无需逐一追溯嵌套缓存链。没有显式的生命周期值,行为就会依赖于内层缓存的生命周期,从而更难推理。

嵌套的短生命周期缓存

如预渲染行为所述,短生命周期缓存(revalidate 为零或 expire 低于 5 分钟)会成为动态空洞,被排除在预渲染之外。

当短生命周期缓存嵌套在另一个未显式指定 cacheLife 的 use cache 中时,通过传播,外层缓存的生命周期也会在无提示的情况下变短。为防止这种意外的错误配置,Next.js 会在预渲染期间抛出错误。

注意,嵌套的缓存可能并不明显——它可能位于某个导入的模块中,甚至是第三方依赖中:

components/short-lived-widget.tsxtsx
import { cacheLife } from 'next/cache'

export async function ShortLivedWidget() {
  'use cache'
  cacheLife('seconds')
  const data = await fetchRealtimeData()
  return <div>{data}</div>
}

在另一个未显式指定 cacheLife 的 use cache 中使用此组件时,预渲染期间会报错:

app/page.tsxtsx
import { ShortLivedWidget } from '@/components/short-lived-widget'

export default async function Page() {
  'use cache'
  // Error: no explicit cacheLife on outer cache
  return (
    <div>
      <h1>Dashboard</h1>
      <p>Last updated: {new Date().toISOString()}</p>
      <ShortLivedWidget />
    </div>
  )
}

要修复该错误,请为外层 use cache 添加显式的 cacheLife():

如果你希望外层缓存保持静态(预渲染),请设置更长的缓存生命周期:

app/page.tsxtsx
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'

export default async function Page() {
  'use cache'
  cacheLife('default') // Explicit cacheLife prevents the error
  return (
    <div>
      <h1>Dashboard</h1>
      <p>Last updated: {new Date().toISOString()}</p>
      <ShortLivedWidget />
    </div>
  )
}

如果你希望外层缓存也是短生命周期的,请显式设置较短的生命周期以确认这是有意为之。将组件包裹在 <Suspense> 边界中,以便在内容加载时提供回退内容:

app/page.tsxtsx
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
import { ShortLivedWidget } from '@/components/short-lived-widget'

async function Content() {
  'use cache: remote'
  cacheLife('seconds') // Explicit cacheLife confirms this is intentionally short-lived
  return (
    <>
      <p>Last updated: {new Date().toISOString()}</p>
      <ShortLivedWidget />
    </>
  )
}

export default function Page() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <Content />
      </Suspense>
    </div>
  )
}

注意:

此示例使用 "use cache: remote",因为在无服务器部署中,使用默认的内存缓存时,运行时缓存无法在多次请求之间持久化。对于自托管环境,"use cache" 可能就足够了。更多详细信息,请参阅运行时缓存注意事项。

条件缓存生命周期

你可以在不同的代码路径中有条件地调用 cacheLife,以根据应用程序逻辑设置不同的缓存时长:

lib/posts.tstsx
import { cacheLife, cacheTag } from 'next/cache'

async function getPostContent(slug: string) {
  'use cache'

  const post = await fetchPost(slug)

  // Tag the cache entry for targeted revalidation
  cacheTag(`post-${slug}`)

  if (!post) {
    // Content may not be published yet or could be in draft
    // Cache briefly to reduce database load
    cacheLife('minutes')
    return null
  }

  // Published content can be cached longer
  cacheLife('days')

  // Return only the necessary data to keep cache size minimal
  return post.data
}

当不同结果需要不同的缓存时长时,此模式很有用,例如,当某个条目缺失但之后可能会变为可用时。

使用来自数据的动态缓存生命周期

如果你希望在运行时计算缓存生命周期,例如从获取的数据中读取它,请使用内联缓存配置对象:

lib/posts.tstsx
import { cacheLife, cacheTag } from 'next/cache'

async function getPostContent(slug: string) {
  'use cache'

  const post = await fetchPost(slug)
  cacheTag(`post-${slug}`)

  if (!post) {
    cacheLife('minutes')
    return null
  }

  // Use cache timing from CMS data directly as an object
  cacheLife({
    // Ensure post.revalidateSeconds is a number in seconds
    // stale and expire inherit from 'default' profile
    revalidate: post.revalidateSeconds ?? 3600,
  })

  return post.data
}

版本历史

版本 变更
v16.0.0 cacheLife 已稳定。unstable_cacheLife 已弃用。

请参阅 Next.js 16 升级指南,将导入从 unstable_cacheLife 更新为 cacheLife。

相关内容

查看相关 API 参考。

  • cacheComponents:了解如何在 Next.js 中启用 cacheComponents 标志。
  • use cache:了解如何使用 "use cache" 指令在 Next.js 应用程序中缓存数据。
  • revalidateTag:revalidateTag 函数的 API 参考。
  • cacheTag:了解如何使用 cacheTag 函数在 Next.js 应用程序中管理缓存失效。