Skip to main content

fetch

Next.js 扩展了 网络 fetch() API,允许服务器上的每个请求设置自己的持久缓存和重新验证语义。

¥Next.js extends the Web fetch() API to allow each request on the server to set its own persistent caching and revalidation semantics.

在浏览器中,cache 选项指示获取请求将如何与浏览器的 HTTP 缓存交互。使用此扩展,cache 指示服务器端获取请求将如何与框架的持久 数据缓存 交互。

¥In the browser, the cache option indicates how a fetch request will interact with the browser's HTTP cache. With this extension, cache indicates how a server-side fetch request will interact with the framework's persistent Data Cache.

你可以直接在服务器组件中使用 asyncawait 调用 fetch

¥You can call fetch with async and await directly within Server Components.

export default async function Page() {
let data = await fetch('https://api.vercel.app/blog')
let posts = await data.json()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
export default async function Page() {
let data = await fetch('https://api.vercel.app/blog')
let posts = await data.json()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}

fetch(url, options)

由于 Next.js 扩展了 网络 fetch() API,因此你可以使用任何 可用的原生选项

¥Since Next.js extends the Web fetch() API, you can use any of the native options available.

options.cache

配置请求应如何与 Next.js 交互 数据缓存

¥Configure how the request should interact with Next.js Data Cache.

fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
  • no-store(默认):Next.js 在每次请求时从远程服务器获取资源,而不查看缓存,并且不会使用下载的资源更新缓存。

    ¥**no-store** (default): Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource.

  • force-cache:Next.js 在其数据缓存中查找匹配的请求。

    ¥**force-cache**: Next.js looks for a matching request in its Data Cache.

    • 如果存在匹配并且是新鲜的,则将从缓存中返回。

      ¥If there is a match and it is fresh, it will be returned from the cache.

    • 如果没有匹配项或匹配项过时,Next.js 将从远程服务器获取资源并使用下载的资源更新缓存。

      ¥If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.

options.next.revalidate

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

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

¥Set the cache lifetime of a resource (in seconds).

  • false - 无限期缓存资源。语义上等同于 revalidate: Infinity。随着时间的推移,HTTP 缓存可能会驱逐较旧的资源。

    ¥**false** - Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time.

  • 0 - 防止资源被缓存。

    ¥**0** - Prevent the resource from being cached.

  • number - (很快)指定资源的缓存生存期最多应为 n 秒。

    ¥**number** - (in seconds) Specify the resource should have a cache lifetime of at most n seconds.

很高兴知道:

¥Good to know:

  • 如果单个 fetch() 请求设置的 revalidate 编号低于路由的 默认 revalidate,则整个路由重新生效间隔将会缩短。

    ¥If an individual fetch() request sets a revalidate number lower than the default revalidate of a route, the whole route revalidation interval will be decreased.

  • 如果同一路由中具有相同 URL 的两个 fetch 请求具有不同的 revalidate 值,则将使用较低的值。

    ¥If two fetch requests with the same URL in the same route have different revalidate values, the lower value will be used.

  • 为方便起见,如果 revalidate 设置为数字,则无需设置 cache 选项。

    ¥As a convenience, it is not necessary to set the cache option if revalidate is set to a number.

  • 冲突的选项(例如 { revalidate: 3600, cache: 'no-store' })将导致错误。

    ¥Conflicting options such as { revalidate: 3600, cache: 'no-store' } will cause an error.

options.next.tags

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

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

¥Set the cache tags of a resource. Data can then be revalidated on-demand using revalidateTag. The max length for a custom tag is 256 characters and the max tag items is 64.

故障排除

¥Troubleshooting

Fetch cache: 'no-store' 未显示开发中的新数据

¥Fetch cache: 'no-store' not showing fresh data in development

Next.js 在本地开发中通过热模块替换 (HMR) 将 fetch 响应缓存在服务器组件中,以加快响应速度并降低计费 API 调用的成本。

¥Next.js caches fetch responses in Server Components across Hot Module Replacement (HMR) in local development for faster responses and to reduce costs for billed API calls.

默认情况下,HMR 缓存 适用于所有获取请求,包括带有 cache: 'no-store' 选项的请求。这意味着未缓存的请求不会在 HMR 刷新之间显示新数据。但是,在导航或整页重新加载时,缓存将被清除。

¥By default, the HMR cache applies to all fetch requests, including those with the cache: 'no-store' option. This means uncached requests will not show fresh data between HMR refreshes. However, the cache will be cleared on navigation or full-page reloads.

有关更多信息,请参阅 serverComponentsHmrCache 文档。

¥See the serverComponentsHmrCache docs for more information.

版本历史

¥Version History

版本变化
v13.0.0fetch 推出。