Explain Codes LogoExplain Codes Logo

Fetch(), how do you make a non-cached request?

javascript
cache-control
fetch-api
browser-cache
Alex KataevbyAlex Kataev·Sep 17, 2024
TLDR

To make a fresh network request with fetch(), use cache: 'no-store'.

fetch('your-endpoint', { cache: 'no-store' }) .then(response => /* process response */) .catch(error => /* handle error */);

Grasping cache control

The browser might store a response in its cache on a fetch request. For subsequent requests for the same resource, the browser may respond with the cached copy rather than making a new network request. If you require the latest data, this can lead to stale content. Therefore, cache control in the fetch API becomes crucial.

Deciphering cache modes

Fetch requests provide a few options for cache control behavior:

  • no-store: Ensures that requests do not cache anything.
  • reload: Forces the browser to bypass the cache and download the whole response again.
  • no-cache: Prompts a revalidation with the server before using the cached response.
  • force-cache: Uses the cache (if available) or fetches as usual, thus conversing bandwidth.

Let's delve deeper into why and how to utilize these options.

##Alternative Cache Control Solutions

While no-store guarantees fresh data, there may be times when you wish to let the browser affirm the stored content's age versus the server's version. Here's how:

Validating cache freshness

Use no-cache to ensure freshness; it compels the browser to submit the request to the server and confirm that the content hasn’t changed before using the cached version.

Case study: Bandwidth optimization

There may be times when you seek to save bandwidth. For this, use the force-cache option: it utilizes cached responses whenever available, thus avoiding the cost of an additional download.

Catering to unique requirements

If your setup includes intermediate caches (like a CDN layer) between the app and server, incorporate the Pragma: no-cache header to bypass all caches and ensure direct server retrieval.

fetch('https://api.example.com/data', { cache: 'no-cache', // The usual suspect headers: { 'Pragma': 'no-cache' // King of the bypass } })

Tips and tricks for real-time data

You can ensure fresh data in real-time applications (like stock prices or live sports scores) by:

  • Combining headers: Using both Cache-Control: no-cache and Pragma: no-cache for assured cache bypass.
  • Processing and displaying: Process and reflect the fetched response instantly for real-time updates.
  • Using the right method: Ensure correct request methods and appropriate cache headers for POST requests, where responses shouldn't be cached.

Examples and Explanations

Here’s how a fetch request can be innovatively written for an image that needs to be the latest version every time:

fetch('https://api.example.com/avatar.png', { cache: 'no-cache', // Playing detective headers: { 'Pragma': 'no-cache' // The spy who came from the cache } }) .then(response => response.blob()) .then(imageBlob => { // Convert blob object into URL, like turning coffee into code const imageURL = URL.createObjectURL(imageBlob); // Update image source directly, faster than changing your mind on a keyboard layout document.querySelector('#user-avatar').src = imageURL; }) .catch(error => console.error('When it comes to fetch image:', "if it ain't right, it ain't right, mate!\nError:", error));

As seen, the cache option is set to 'no-cache', and we have a 'Pragma: no-cache' header. Together, they ensure fetch bypasses all cached versions to retrieve a fresh copy.

Traps and their fixes

Browser disparities

Every browser handles caching differently. Test fetch requests across all target browsers to ensure consistency.

Ignoring headers in POST requests

Although POST responses are not usually cached, specifying no-cache or no-store is a surefire method to prevent unwanted caching.

Not validating cache control

After implementing cache control, use helpful tools such as network inspectors to check if requests operate as planned.