1

I have a XMLHttpRequest that does a GET request:

const xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "myapi/getThing", true)

Normally, the response stays the same so the server instructs to cache it with a HTTP response header:

Cache-Control: public, max-age=604800, immutable

However, now I perform an action that I know for a fact will change the response, and so I call a XMLHttpRequest again, but the result won't change because of caching.

How do I make it so the next XHR call of this resource won't use the browser cache?

I have tried setting the Cache-Control to no-cache on the request:

xmlHttp.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0")

But the browser still uses the cache.

The goal is to explicitly NOT change the caching policy the server sets for performance reasons, so no validation and such. This should purely be the client wanting a 'fresh resource' on demand.

Fudge Fudge
  • 1,024
  • 1
  • 10
  • 25
  • 1
    a possible solution is to send any query param (even if it does nothing) to bust the cache. `myapi/getThing?a=1` - https://stackoverflow.com/questions/9692665/cache-busting-via-params – Andrew Lohr Sep 22 '21 at 19:23
  • Unfortunately that doesn't work for the next time `myapi/getThing` is called. – Fudge Fudge Sep 22 '21 at 19:42
  • You can write code to generate a random string or number in place of `1` right before the request. – Andrew Lohr Sep 22 '21 at 19:49
  • Looks like you misunderstood what I meant. I meant that when the page is reloaded, `myapi/getThing` is called again normally, and suddenly this 'deleted' cache 'comes back'. – Fudge Fudge Sep 22 '21 at 20:04
  • Using `Cache-Control: no-cache` on the request is the way to do this, not sure why it isn't working for you. Try it in more than one browser. – Kevin Christopher Henry Sep 22 '21 at 21:02

2 Answers2

1

An effective solution:
Cache busting via params
Assuming the server supports adding a useless parameter.

Fudge Fudge
  • 1,024
  • 1
  • 10
  • 25
0

I think both options could work, with cache busting as @Fudge Fudge suggested being the most frequently deployed one, something like:

xhtp.open("YOUR_METHOD","your_url?" + (Math.random() * 1e16).toString(16))

or you can use Date.now() etc., its up to you, sufficiently random number to guarantee uniqueness is enough.

The other way, would be to:

xhtp.setRequestHeader("Cache-Control","no-cache, no-store, must-revalidate");
xhtp.setRequestHeader("Pragma","no-cache");
xhtp.setRequestHeader("Expires","0");

sometimes old headers like Expires etc. can get the job done.

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22