mjs
mjs

Reputation: 65343

Does the service worker cache support cache-control headers?

Does the service worker cache support cache-control headers? For example, if an entry in the cache has the headers cache-control: no-store or cache-control: max-age=60 are these respected by match()?

The following code outputs CACHE HIT despite the header cache-control: no-store appearing in the response. (I think the same problem applies to max-age.)

function warm(c) {
  var req = new Request("/foo.txt");
  var res = new Response("hello", {
    status: 200,
    statusText: "OK",
    headers: new Headers({
      "cache-control": "no-store",
      "content-type": "text/plain"
    })
  });
  return c.put(req, res).then(function () { return c; });
}

function lookup(c) {
  return c.match(new Request("/foo.txt")).then(function (r) {
    return r ? "CACHE HIT" : "CACHE MISS";
  });
}

function deleteAllCaches() {
  return caches.keys().then(function (cacheNames) {
    return Promise.all(
      cacheNames.map(function (cacheName) {
        return caches.delete(cacheName);
      })
    );
  });
}

self.addEventListener('install', function (event) {
  event.waitUntil(
    deleteAllCaches()
    .then(caches.open.bind(caches, 'MYCACHE'))
    .then(warm)
    .then(lookup)
    .then(console.log.bind(console))
    .then(function () { return true; })
  );
});

Upvotes: 2

Views: 1391

Answers (1)

mjs
mjs

Reputation: 65343

The service worker cache does not behave like a standard RFC-compliant HTTP cache. In particular, it ignores all headers that relate to "freshness" (such as cache-control). Note, however, that it does behave as expected with respect to the vary header. (See the cache resolution algorithm in the spec.)

If you want HTTP-compliant cache behavior you'll need to layer this on top of the existing cache's features.

Upvotes: 5

Related Questions