skip to Main Content

I may be fundamentally misunderstanding something here but it seems to me that if I want to fetch something I can call

let r = await fetch("someurl");

and the browser will use a cached version if it has one. Or I could call

let r = await fetch("someurl", {
  cache: "reload"
});

and I would always get a new version.

What I cannot find is how to tell it that I only want the cached version if it is younger than X minutes.

I could do

let r = await fetch("someurl", {
  headers: {
    "Cache-control": "max-age=180"
  }
});

but afaiu that would just get sent to the server and not actually impact what the browser is doing about values in its own cache.

2

Answers


  1. You’re on the right track, but your understanding is slightly off. When you use the cache option in the fetch API, you’re controlling how the browser fetches resources from its cache or from the network. The "reload" option does indeed force the browser to bypass its cache and fetch a fresh version from the network.

    Login or Signup to reply.
  2. In theory you can actually do exactly what you said:

    let r = await fetch("someurl", {
      headers: {
        "Cache-Control": "max-age=180"
      }
    });
    

    That’s because Cache-Control is a request header as well as a response header:

    The max-age request directive indicates that the client prefers a response whose age is less than or equal to the specified number of seconds.

    My impression in the past was that browser caches don’t respect this request header, though, so I’m not sure offhand how well this will work in practice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search