cache option in fetch API
In fetch
API, the cache
option is used to control the caching behavior of the request. The cache
option allows you to specify how the browser should handle caching for a particular request. Here are the possible values you can use with the cache
option:
cache
Option Values
-
default
: This is the default value. The browser will use its default caching behavior based on the HTTP headers in the response. -
no-store
: This value indicates that the browser should not store any part of the request or response in any cache. This is useful when you want to ensure that the data is always fetched from the server and not from any cache. It is a strong directive to avoid caching. -
reload
: This value forces the browser to fetch the resource from the network, ignoring any cached versions. This is similar tono-cache
but with a different behavior. It fetches the resource from the server but may use cache headers to decide if it should be cached again. -
no-cache
: This value tells the browser to fetch the resource from the server and then check if it can be cached based on the cache headers. It doesn’t use the cached version if it exists but checks if the server’s response is different from the cached version. -
force-cache
: This value forces the browser to use a cached response if one is available. If no cached response is available, it will fetch the resource from the network. -
only-if-cached
: This value tells the browser to only use a cached response and not to fetch from the network at all. If there is no cached response, it will result in a network error.
Example Usage
Here’s how you might use the cache
option in a fetch
request:
// Fetch with no caching
fetch('https://api.example.com/data', {
cache: 'no-store' // Ensures no part of the request or response is cached
})
.then(response => response.json())
.then(data => console.log(data));
// Fetch with cache
fetch('https://api.example.com/data', {
cache: 'force-cache' // Use cached response if available
})
.then(response => response.json())
.then(data => console.log(data));
// Fetch with reload
fetch('https://api.example.com/data', {
cache: 'reload' // Fetch from the network and update cache
})
.then(response => response.json())
.then(data => console.log(data));
In Short
no-store
: Prevents any caching; always fetches from the network.no-cache
: Fetches from the network and checks cache validity.force-cache
: Uses the cached response if available.only-if-cached
: Uses only cached responses, no network request.reload
: Fetches from the network, and may update the cache.