If you want to improve your web application's performance, caching with the Fetch API can help you achieve just that!
Caching allows you to store responses from previous requests so you can retrieve them faster the next time they're needed. This reduces the amount of time it takes to load content on your page and the number of requests your application needs to make to the server.
When using the Fetch API for caching, it's important to understand the different cache modes available to you. By specifying a cache mode, you can control how the browser handles caching and when it should make network requests. Here's a brief overview of the six different cache modes:
This is the default cache mode and allows the browser to decide whether to use a cached response or make a new network request based on the standard HTTP caching headers.
This mode disables caching altogether and requires the browser to request a new network whenever the resource is requested.
This mode requires the browser to always make a new network request, ignoring cached responses.
This mode allows the browser to cache responses but requires it to revalidate the cached response with the server before using it.
This mode instructs the browser to always use the cached response and never make a new network request, even if the cached response has expired.
This mode allows the browser to use a cached response only if it's available. If the cached response isn't available, the browser returns a network error.
To implement caching with Fetch API, we can make use of the browser's Cache API to store responses from network requests. Caching responses can help to avoid unnecessary network requests and improve the overall performance of web applications.
Let’s take a look at how we can cache HTTP requests.
In this example, let’s use the Famous Quotes API from RapidAPI hub to fetch a random quote.
js
const apiUrl ='https://famous-quotes4.p.rapidapi.com/random?count=1&category=all';// Make an api request using Fetch APIfetch(apiUrl, {cache: 'no-cache',headers: {'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com','x-rapidapi-key': 'YOUR_RAPID_KEY'}}).then(response => response.json()).then(response => console.log(response)).catch(error => {console.error('Error:', error);});
As you can see, we have added a cache
key that has a value of no-cache
to save our API response in the browser cache.
In general, it's not a good idea to cache POST requests because the data in the request body could be sensitive or could change frequently. However, if you need to cache a POST request, you can do so by including the request body in the cache key.
Caching with the Fetch API can greatly improve the performance of web applications by reducing the number of network requests and speeding up page load times. To take advantage of caching, it's important to set appropriate cache headers, use caching libraries, and cache only cacheable requests.