fetch

Next.js 扩展了原生的 Web fetch() API,允许服务端的每个请求设置自己的持久化缓存语义。

在浏览器中,cache 选项表示 fetch 请求如何与 浏览器 的 HTTP 缓存交互。通过此扩展,cache 选项表示 服务端 fetch 请求如何与框架的持久化 HTTP 缓存交互。

您可以直接在服务端组件 (Server Components) 中使用 asyncawait 调用 fetch

export default async function Page() {
  // 此请求应缓存直至手动失效
  // 类似于 `getStaticProps`
  // `force-cache` 是默认值,可省略
  const staticData = await fetch(`https://...`, { cache: 'force-cache' })

  // 此请求应在每次请求时重新获取
  // 类似于 `getServerSideProps`
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' })

  // 此请求应缓存 10 秒
  // 类似于带 `revalidate` 选项的 `getStaticProps`
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  })

  return <div>...</div>
}

fetch(url, options)

由于 Next.js 扩展了 Web fetch() API,您可以使用所有 原生支持的选项

options.cache

配置请求如何与 Next.js 数据缓存 (Data Cache) 交互。

fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
  • force-cache (默认值) - Next.js 会在其数据缓存中查找匹配的请求。
    • 如果找到匹配且未过期,则从缓存返回。
    • 如果没有匹配或已过期,Next.js 会从远程服务器获取资源并更新缓存。
  • no-store - Next.js 每次请求都会直接从远程服务器获取资源,不查询缓存,且不会更新缓存。

须知

  • 如果不提供 cache 选项,Next.js 会默认使用 force-cache,除非使用了 动态函数 (dynamic functions)cookies(),此时会默认使用 no-store
  • 在 Next.js 中,no-cache 选项的行为与 no-store 相同。

options.next.revalidate

fetch(`https://...`, { next: { revalidate: false | 0 | number } })

设置资源的缓存生命周期(单位:秒)。

  • false - 无限期缓存资源。语义上等同于 revalidate: Infinity。HTTP 缓存可能会随时间推移淘汰旧资源。
  • 0 - 禁止缓存资源。
  • number - (单位:秒)指定资源最多缓存 n 秒。

须知

  • 如果单个 fetch() 请求设置的 revalidate 数值小于路由的 默认 revalidate,整个路由的重新验证间隔会缩短。
  • 如果同一路由中相同 URL 的两个 fetch 请求设置了不同的 revalidate 值,将采用较小的值。
  • 为方便起见,如果设置了 revalidate 数值,则无需设置 cache 选项,因为 0 表示 cache: 'no-store',正数表示 cache: 'force-cache'
  • 冲突的选项如 { revalidate: 0, cache: 'force-cache' }{ revalidate: 10, cache: 'no-store' } 会导致错误。

options.next.tags

fetch(`https://...`, { next: { tags: ['collection'] } })

设置资源的缓存标签。之后可以使用 revalidateTag 按需重新验证数据。自定义标签的最大长度为 256 个字符。

版本历史

版本变更
v13.0.0引入 fetch 功能。

On this page