NNext.js 中文网 GitHub

缓存与重新验证(旧模型)

了解对于未使用 Cache Components 的项目,如何使用 fetch 选项、unstable_cache 和路由段配置来缓存和重新验证数据。

本指南假定你没有使用 Cache Components,它是在版本 16 中通过 cacheComponents 标志引入的。

缓存 fetch 请求#

默认情况下,fetch 请求不会被缓存。你可以通过将 cache 选项设置为 'force-cache' 来缓存单个请求。

app/page.tsx
export default async function Page() {
  const data = await fetch('https://...', { cache: 'force-cache' })
}
app/page.jsx
export default async function Page() {
  const data = await fetch('https://...', { cache: 'force-cache' })
}

请参阅 fetch API 参考以了解更多。

用于非 fetch 函数的 unstable_cache#

unstable_cache 允许你缓存数据库查询的结果以及其他不使用 fetch 的异步函数。用 unstable_cache 包裹该函数:

app/lib/data.ts
import { unstable_cache } from 'next/cache'
import { db } from '@/lib/db'

export const getCachedUser = unstable_cache(
  async (id: string) => {
    return db
      .select()
      .from(users)
      .where(eq(users.id, id))
      .then((res) => res[0])
  },
  ['user'], // 缓存键前缀
  {
    tags: ['user'],
    revalidate: 3600,
  }
)
app/lib/data.js
import { unstable_cache } from 'next/cache'
import { db } from '@/lib/db'

export const getCachedUser = unstable_cache(
  async (id) => {
    return db
      .select()
      .from(users)
      .where(eq(users.id, id))
      .then((res) => res[0])
  },
  ['user'], // 缓存键前缀
  {
    tags: ['user'],
    revalidate: 3600,
  }
)

第三个参数接受:

  • tags:用于通过 revalidateTag 进行按需重新验证的标签数组。
  • revalidate:缓存重新验证前的秒数。

请参阅 unstable_cache API 参考以了解更多。

路由段配置#

你可以通过从 Page、Layout 或 Route Handler 中导出配置选项,在路由级别配置缓存行为。

dynamic#

将布局或页面的动态行为更改为完全静态或完全动态。

layout.tsx | page.tsx | route.ts
export const dynamic = 'auto'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
layout.js | page.js | route.js
export const dynamic = 'auto'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
  • 'auto'(默认):默认选项,尽可能多地缓存,同时不阻止任何组件选择动态行为。
  • 'force-dynamic':强制动态渲染,这将导致路由在请求时为每个用户进行渲染。此选项等价于:
    • 将布局或页面中每个 fetch() 请求的选项设置为 { cache: 'no-store', next: { revalidate: 0 } }。
    • 将段配置设置为 export const fetchCache = 'force-no-store'
  • 'error':如果任何组件使用请求时 API 或未缓存的数据,则通过引发错误来强制预渲染并缓存布局或页面的数据。此选项等价于:
    • pages 目录中的 getStaticProps()。
    • 将布局或页面中每个 fetch() 请求的选项设置为 { cache: 'force-cache' }。
    • 将段配置设置为 fetchCache = 'only-cache'。
  • 'force-static':通过强制 cookies、headers() 和 useSearchParams() 返回空值,来强制预渲染并缓存布局或页面的数据。在以 force-static 渲染的页面或布局中,仍然可以进行 revalidate、revalidatePath 或 revalidateTag。

fetchCache#

<details> <summary>这是一个高级选项,仅当你确实需要覆盖默认行为时才应使用。</summary>

一个没有设置 cache 选项的 fetch 请求,如果在使用任何请求时 API 之前可到达,那么它会在 next build 期间被获取一次,因为路由会预渲染到该位置。在请求时 API 之后发现的请求则会在每次请求时运行。

fetchCache 允许你覆盖布局或页面中所有 fetch 请求的默认 cache 选项。

layout.tsx | page.tsx | route.ts
export const fetchCache = 'auto'
// 'auto' | 'default-cache' | 'only-cache'
// 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store'
layout.js | page.js | route.js
export const fetchCache = 'auto'
// 'auto' | 'default-cache' | 'only-cache'
// 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store'
  • 'auto'(默认):默认选项,在使用请求时 API 之前,使用 fetch 请求提供的 cache 选项对其进行缓存,而不缓存请求时 API 之后的 fetch 请求。
  • 'default-cache':允许向 fetch 传递任何 cache 选项,但如果未提供选项,则将 cache 选项设置为 'force-cache'。这意味着即使是请求时 API 之后的 fetch 请求也会被视为静态。
  • 'only-cache':如果没有提供选项,则将默认值更改为 cache: 'force-cache',并在任何 fetch 请求使用 cache: 'no-store' 时引发错误,从而确保所有 fetch 请求都选择加入缓存。
  • 'force-cache':通过将所有 fetch 请求的 cache 选项设置为 'force-cache',确保所有 fetch 请求都选择加入缓存。
  • 'default-no-store':允许向 fetch 传递任何 cache 选项,但如果未提供选项,则将 cache 选项设置为 'no-store'。这意味着即使是请求时 API 之前的 fetch 请求也会被视为动态。
  • 'only-no-store':如果没有提供选项,则将默认值更改为 cache: 'no-store',并在任何 fetch 请求使用 cache: 'force-cache' 时引发错误,从而确保所有 fetch 请求都选择退出缓存。
  • 'force-no-store':通过将所有 fetch 请求的 cache 选项设置为 'no-store',确保所有 fetch 请求都选择退出缓存。这会强制所有 fetch 请求在每次请求时重新获取,即使它们提供了 'force-cache' 选项。
跨路由段行为#
  • 在单个路由的各个布局和页面中设置的所有选项都需要彼此兼容。
    • 如果同时提供了 'only-cache' 和 'force-cache',则 'force-cache' 优先。如果同时提供了 'only-no-store' 和 'force-no-store',则 'force-no-store' 优先。force 选项会改变整个路由的行为,因此单个带有 'force-*' 的段可以防止由 'only-*' 引起的任何错误。
    • 'only-*' 和 'force-*' 选项的意图是保证整个路由要么完全静态,要么完全动态。这意味着:
      • 不允许在单个路由中组合使用 'only-cache' 和 'only-no-store'。
      • 不允许在单个路由中组合使用 'force-cache' 和 'force-no-store'。
    • 如果子级提供了 'auto' 或 '*-cache',则父级不能提供 'default-no-store',因为这可能导致同一个 fetch 具有不同的行为。
  • 通常建议将共享的父级布局保持为 'auto',并在子段出现分歧的地方自定义选项。

</details>

基于时间的重新验证#

使用 fetch 上的 next.revalidate 选项,在指定的秒数后重新验证数据:

app/page.tsx
export default async function Page() {
  const data = await fetch('https://...', { next: { revalidate: 3600 } })
}
app/page.jsx
export default async function Page() {
  const data = await fetch('https://...', { next: { revalidate: 3600 } })
}

对于非 fetch 函数,unstable_cache 在其配置中接受 revalidate 选项(请参阅上面的示例)。

路由段配置 revalidate#

设置布局或页面的默认重新验证时间。此选项不会覆盖由单个 fetch 请求设置的 revalidate 值。

layout.tsx | page.tsx | route.ts
export const revalidate = false
// false | 0 | number
layout.js | page.js | route.js
export const revalidate = false
// false | 0 | number
  • false(默认):默认的启发式行为,缓存任何将 cache 选项设置为 'force-cache' 的 fetch 请求,或在使用请求时 API 之前发现的请求。在语义上等价于 revalidate: Infinity,这实际上意味着资源应被无限期缓存。单个 fetch 请求仍然可以使用 cache: 'no-store' 或 revalidate: 0 来避免被缓存,从而使路由动态渲染。或者将 revalidate 设置为低于路由默认值的正数,以提高路由的重新验证频率。
  • 0:确保布局或页面始终动态渲染,即使没有发现请求时 API 或未缓存的数据获取。此选项会将未设置 cache 选项的 fetch 请求的默认值更改为 'no-store',但会保留选择加入 'force-cache' 或使用正数 revalidate 的 fetch 请求不变。
  • number:(以秒为单位)将布局或页面的默认重新验证频率设置为 n 秒。

小知识:

  • revalidate 值需要是可静态分析的。例如 revalidate = 600 是有效的,但 revalidate = 60 * 10 则无效。
  • 使用已弃用的 runtime = 'edge' 时,revalidate 值不可用。
  • 在开发环境中,页面始终按需渲染,永远不会被缓存。这使你能够立即看到更改,而无需等待重新验证周期结束。

重新验证频率#

  • 单个路由中各个布局和页面里最小的 revalidate 值将决定整个路由的重新验证频率。这确保子页面的重新验证频率与其父布局一样频繁。
  • 单个 fetch 请求可以设置比路由默认 revalidate 更低的 revalidate,以提高整个路由的重新验证频率。这使你能够根据某些条件动态地为特定路由选择更频繁的重新验证。

按需重新验证#

要在某个事件后重新验证缓存数据,请在 Server Action 或 Route Handler 中使用 revalidateTag 或 revalidatePath。

为缓存数据添加标签#

使用 next.tags 为 fetch 请求添加标签,以启用按需缓存失效:

app/lib/data.ts
export async function getUserById(id: string) {
  const data = await fetch(`https://...`, {
    next: { tags: ['user'] },
  })
}
app/lib/data.js
export async function getUserById(id) {
  const data = await fetch(`https://...`, {
    next: { tags: ['user'] },
  })
}

对于非 fetch 函数,unstable_cache 也接受 tags 选项(请参阅上面的示例)。

revalidateTag#

使用 revalidateTag 按标签使缓存数据失效:

app/lib/actions.ts
import { revalidateTag } from 'next/cache'

export async function updateUser(id: string) {
  // 修改数据
  revalidateTag('user', 'max')
}
app/lib/actions.js
import { revalidateTag } from 'next/cache'

export async function updateUser(id) {
  // 修改数据
  revalidateTag('user', 'max')
}

revalidatePath#

使用 revalidatePath 使特定路由路径的所有缓存数据失效:

app/lib/actions.ts
import { revalidatePath } from 'next/cache'

export async function updateUser(id: string) {
  // 修改数据
  revalidatePath('/profile')
}
app/lib/actions.js
import { revalidatePath } from 'next/cache'

export async function updateUser(id) {
  // 修改数据
  revalidatePath('/profile')
}

请求去重#

如果你没有使用 fetch(它会被自动记忆化),而是直接使用 ORM 或数据库,你可以用 React cache 函数包裹你的数据访问,从而在单次渲染过程中对请求进行去重:

app/lib/data.ts
import { cache } from 'react'
import { db, posts, eq } from '@/lib/db'

export const getPost = cache(async (id: string) => {
  const post = await db.query.posts.findFirst({
    where: eq(posts.id, parseInt(id)),
  })
})
app/lib/data.js
import { cache } from 'react'
import { db, posts, eq } from '@/lib/db'

export const getPost = cache(async (id) => {
  const post = await db.query.posts.findFirst({
    where: eq(posts.id, parseInt(id)),
  })
})

预加载数据#

你可以通过创建一个实用函数,并在阻塞请求之前主动调用它来预加载数据。这使你能够尽早发起数据获取,从而在组件渲染时数据已经可用。

将 server-only 包与 React 的 cache 结合使用,创建一个可重用的预加载实用函数:

utils/get-item.ts
import { cache } from 'react'
import 'server-only'

export const getItem = cache(async (id: string) => {
  // ...
})

export const preload = (id: string) => {
  void getItem(id)
}
utils/get-item.js
import { cache } from 'react'
import 'server-only'

export const getItem = cache(async (id) => {
  // ...
})

export const preload = (id) => {
  void getItem(id)
}

然后在任何阻塞工作之前调用 preload(),以便数据立即开始加载:

app/item/[id]/page.tsx
import { getItem, preload, checkIsAvailable } from '@/lib/data'

export default async function Page({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  // 开始加载商品数据
  preload(id)
  // 执行另一个异步任务
  const isAvailable = await checkIsAvailable()

  return isAvailable ? <Item id={id} /> : null
}

async function Item({ id }: { id: string }) {
  const result = await getItem(id)
  // ...
}
app/item/[id]/page.js
import { getItem, preload, checkIsAvailable } from '@/lib/data'

export default async function Page({ params }) {
  const { id } = await params
  // 开始加载商品数据
  preload(id)
  // 执行另一个异步任务
  const isAvailable = await checkIsAvailable()

  return isAvailable ? <Item id={id} /> : null
}

async function Item({ id }) {
  const result = await getItem(id)
  // ...
}

静态生成动态路由#

要使用 generateStaticParams 预渲染动态路由并随时间重新验证它们,请参阅 Incremental Static Regeneration 指南。

Next.js 中文网