bestfetch includes a sophisticated system for caching responses.
Use the cachePolicy
option when calling bestfetch()
to control when the cache is used. Supported values are:
"cache-first"
: The cache is checked to see if a response already exists for the request. If a response is found, then it will be returned, and no network request will be made. If no response exists in the cache, then a network request will be made."network-only"
: The cache is ignored, and a network request is always made."cache-only"
: If a response exists in the cache, then it will be returned. If no response exists in the cache, then the Promise will reject to a CacheMissError.The following example shows how to specify the "network-only"
option:
bestfetch('/api/books/2', { cachePolicy: 'network-only' })
.then(res => {
console.log('Got the book', res.data);
});
The default value of cache-policy
is determined by the methed of the request:
cachePolicy
GET
"cache-first"
POST
"network-only"
PUT
"network-only"
PATCH
"network-only"
DELETE
"network-only"
The default value for less commonly used methods is:
cachePolicy
HEAD
"cache-first"
OPTIONS
"cache-first"
The default behavior is designed to work for traditional "RESTful" APIs. There are a couple of common situations where this default will not work, and where you will need to specify cachePolicy
yourself:
POST
for all requests (queries and for mutations).POST
for retrieving data instead of GET
.Responses that are added to the cache are never invalidated unless you configure how you would like for them to be invalidated. For more, refer to the guide on invalidating cached responses.
There may come a time when you need to directly read or write to the response cache. You can use the responseCache
export from this library to do this. Learn more in the API documentation for responseCache
.
To learn more about how this algorithm works, and also how you can change its behavior, check out the Identical Requests guide.