Next.js extends the native Web fetch()
API to allow each request on the server to set its own persistent caching semantics.
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 HTTP cache.
You can call fetch
with async
/await
directly within Server Components.
export default async function Page() {
// This request should be cached until manually invalidated.
// Similar to `getStaticProps`.
// `force-cache` is the default and can be omitted.
const staticData = await fetch(`https://...`, { cache: 'force-cache' });
// This request should be refetched on every request.
// Similar to `getServerSideProps`.
const dynamicData = await fetch(`https://...`, { cache: 'no-store' });
// This request should be cached with a lifetime of 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, {
next: { revalidate: 10 },
});
return <div>...</div>;
}
fetch(url, options)
Since Next.js extends the Web fetch()
API, you can use any of the native options available.
Further, Next.js polyfills fetch
on both the client and the server, so you can use fetch in both Server and Client Components.
options.cache
Configure how the request should interact with Next.js HTTP cache.
fetch(`https://...`, { cache: 'force-cache' | 'no-store' });
force-cache
(default) - Next.js looks for a matching request in its HTTP cache.no-store
- 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.Good to know:
cache
option, Next.js will default to force-cache
, unless a dynamic function such as cookies()
is used, in which case it will default to no-store
.no-cache
option behaves the same way as no-store
in Next.js.options.next.revalidate
fetch(`https://...`, { next: { revalidate: false | 0 | number } } });
Set the cache lifetime of a resource (in seconds).
false
- Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity
. The HTTP cache may evict older resources over time.0
- Prevent the resource from being cached.number
- (in seconds) Specify the resource should have a cache lifetime of at most n
seconds.Good to know:
fetch()
request sets a revalidate
number lower than the default revalidate
of a route, the whole route revalidation interval will be decreased. revalidate
values, the lower value will be used.cache
option if revalidate
is set to a number since 0
implies cache: 'no-store'
and a positive value implies cache: 'force-cache'
.{ revalidate: 0, cache: 'force-cache' }
or { revalidate: 10, cache: 'no-store' }
will cause an error.