跳到主要内容

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' })
  • auto no cache(默认):Next.js 在开发过程中的每个请求中都会从远程服务器获取资源,但在 next build 期间只会获取一次,因为路由将被静态预渲染。如果在路由上检测到 动态 API,Next.js 将在每次请求时获取资源。

    ¥**auto no cache** (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during next build because the route will be statically prerendered. If Dynamic APIs are detected on the route, Next.js will fetch the resource on every request.

  • no-store:Next.js 在每个请求中都会从远程服务器获取资源,即使在路由上未检测到动态 API。

    ¥**no-store**: Next.js fetches the resource from the remote server on every request, even if Dynamic APIs are not detected on the route.

  • 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 个字符,最大标签项为 128 个。

¥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 128.

故障排除

¥Troubleshooting

获取默认 auto no storecache: 'no-store' 未在开发中显示新数据

¥Fetch default auto no store and 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 缓存 适用于所有获取请求,包括具有默认 auto no cachecache: 'no-store' 选项的请求。这意味着未缓存的请求不会在 HMR 刷新之间显示新数据。但是,在导航或整页重新加载时,缓存将被清除。

¥By default, the HMR cache applies to all fetch requests, including those with the default auto no cache and 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 推出。