2

I want to get the response headers of a cached response inside a service worker. The purpose of this is so that I can read a custom header called 'Modified' to see if it is necessary to fetch a new copy of the data by comparing it to the response headers of a 'HEAD' fetch for the same URL.

On install of the service worker, I populate a cache called v1::fundamentals with some responses. I then register a fetch listener which looks for the request in the cache and if its there, serves it. I then want to async update the cache with non-stale content but only if the 'Modified' header contains a newer timestamp than the one in the cache. In the simplified code below, I try to access the headers with headers.get() but I always get a null in return. Why is this?

When I look at the cache in Chrome devtools, the headers are very much there, I just can't get to them from within the service worker.

self.addEventListener('fetch', event => {
  console.log('%c[SW] Fetch caught: ', 'color: #42d9f4', event.request.url);

  // Let the browser do its default thing for non-GET requests.
  if (event.request.method != 'GET') {
    return;
  } else {
    // Prevent the default, and handle the request ourselves.
    event.respondWith(async function() {
      // Try to get the response from a cache.
      const cache = await caches.open('v1::fundamentals');
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // Try to get the headers
        var cacheDate = cachedResponse.headers.get('Modified');
        // Print header, returns 'null'
        console.log(cacheDate);

        event.waitUntil(cache.add(event.request));

        return cachedResponse;
      }

      return fetch(event.request);
    }());
  }
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
jupitreas
  • 56
  • 2
  • If you look in the Network panel, do these requests actually have a `Modified` response header? – T.J. Crowder Sep 10 '18 at 15:21
  • Yes, they do, the backend has been configured to serve those. With this said, trying to get a standard header such as 'Date' similarly returns null. – jupitreas Sep 10 '18 at 15:29
  • But I mean, do you see them in the browser's network tab? Just in case the server config isn't quite right, or something is stripping them out, etc... – T.J. Crowder Sep 10 '18 at 16:16
  • 2
    Yes, indeed I do, it is there. Furthermore, the 'Modified' header is just a specific example, I am unable to get any header using the method shown in the question. I am thinking that it might be an async issue but I'd expect it to return a [Promise] instead of just null, and using `let cacheDate = await cachedResponse.headers.get('Modified');` also returns null. – jupitreas Sep 10 '18 at 20:51
  • @jupitreas man you saved my life with this... <333 i upvoted and i really appreciate your help. – Alixsep Aug 12 '21 at 01:48

0 Answers0