177

with fetch('somefile.json'), it is possible to request that the file be fetched from the server and not from the browser cache?

in other words, with fetch(), is it possible to circumvent the browser's cache?

2

4 Answers 4

228

Easier use of cache modes:

  // Download a resource with cache busting, to bypass the cache
  // completely.
  fetch("some.json", {cache: "no-store"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with cache busting, but update the HTTP
  // cache with the downloaded resource.
  fetch("some.json", {cache: "reload"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with cache busting when dealing with a
  // properly configured server that will send the correct ETag
  // and Date headers and properly handle If-Modified-Since and
  // If-None-Match request headers, therefore we can rely on the
  // validation to guarantee a fresh response.
  fetch("some.json", {cache: "no-cache"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with economics in mind!  Prefer a cached
  // albeit stale response to conserve as much bandwidth as possible.
  fetch("some.json", {cache: "force-cache"})
    .then(function(response) { /* consume the response */ });

refrence:https://hacks.mozilla.org/2016/03/referrer-and-cache-control-apis-for-fetch/

9
  • 1
    This is a more appropriate answer. You can handle headers like 'If-Modified-Since' and 'If-None-Match' by these options.
    – Nigiri
    Commented Mar 15, 2017 at 7:57
  • 10
    This seems to work in Firefox (54) but not Chrome (60). burningfuses's answer does work.
    – Scimonster
    Commented Aug 15, 2017 at 12:10
  • 4
    I have tested it, and as for today (November 2019) this method seems to be working on Opera, Chrome and FireFox on both Windows, Linux and Android. The burningfuses method fails at least on Opera. Commented Nov 27, 2019 at 15:09
  • 3
    This respects CORS unlike the winning answer.
    – skrat
    Commented Dec 15, 2020 at 2:55
  • 2
    You may like to read HTTP caching - HTTP | MDN.
    – li ki
    Commented Sep 13, 2022 at 16:55
158

Fetch can take an init object containing many custom settings that you might want to apply to the request, this includes an option called "headers".

The "headers" option takes a Header object. This object allows you to configure the headers you want to add to your request.

By adding pragma: no-cache and a cache-control: no-cache to your header you will force the browser to check the server to see if the file is different from the file it already has in the cache. You could also use cache-control: no-store as it simply disallows the browser and all intermediate caches to store any version of the returned response.

Here is a sample code:

var myImage = document.querySelector('img');

var myHeaders = new Headers();
myHeaders.append('pragma', 'no-cache');
myHeaders.append('cache-control', 'no-cache');

var myInit = {
  method: 'GET',
  headers: myHeaders,
};

var myRequest = new Request('myImage.jpg');

fetch(myRequest, myInit)
  .then(function(response) {
    return response.blob();
  })
  .then(function(response) {
    var objectURL = URL.createObjectURL(response);
    myImage.src = objectURL;
  });
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ES6</title>
</head>
<body>
    <img src="">
</body>
</html>

4
  • 7
    What about using new Request and passing some argument to the cache options? I am trying to use that, but it does not work.
    – Mitar
    Commented Jan 21, 2016 at 7:05
  • 1
    Does the capitalization of the headers matter? I.e. "Cache-Control" vs "cache-control". Commented Aug 29, 2018 at 20:29
  • 5
    @IsaacLyman, although HTTP headers are case-insensitive, I suggest you follow the proposed documentation, which is: "Cache-Control". Reference: developer.mozilla.org/en-US/docs/Web/HTTP/Headers Commented Aug 30, 2018 at 0:26
  • 1
    To add a modern tidbit: For HTTP/2 validation HTTP headers must be all lower-case. (Just the header name, not the value). I speculate the reason is that they want to eliminate the need for toLowerCase algorithms server-side, for mostly security reasons (less attack surface).
    – AnorZaken
    Commented Jul 22, 2022 at 18:21
34

None of the solutions seemed to work well for me, but this relatively clean (AFAICT) hack did work (adapted from https://webmasters.stackexchange.com/questions/93594/prevent-browser-from-caching-text-file):

  const URL = "http://example.com";
  const ms = Date.now();
  const data = await fetch(URL+"?dummy="+ms)
    .catch(er => game_log(er.message))
    .then(response => response.text());

This is just adding a dummy parameter that changes on every call to a query. By all means, if other solutions appear to work, I suggest using those, but in my tests, they did not work in my case (e.g. those using Cache-Control and pragram).

3
  • 3
    Thank you! This is only thing that worked for me.
    – d0g
    Commented Dec 22, 2020 at 23:48
  • A bit outdated but find this thread searching for the same issue The checked answer didn't work for my case (@%#$ CORS) as well? so first I take this hack/workaround but after find that it's can be done with set cache options (to 'no-store') directly as props in fetch options, not as part of a header props
    – Poul
    Commented Sep 9, 2022 at 21:15
  • To future readers: This is the nuclear option. While this will definitely work, if you find that the accepted answer is not working, it may be that you have serverside/edge caching enabled (like Varnish or Squid). You could end up being charged for resource usage when a cached version is available. If every request is guaranteed to be unique, then this is not an issue, but if you only want the response to change at your discretion, you should consult the documentation for your edge cache server and purge the cache there instead.
    – andrew
    Commented Mar 5 at 5:57
28

You can set 'Cache-Control': 'no-cache' in the header like this::

return fetch(url, {
  headers: {
    'Cache-Control': 'no-cache'
  }
}).then(function (res) {
  return res.json();
}).catch(function(error) {
  console.warn('Failed: ', error);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.