Cache storage is empty when using workbox with CDN

Viewed 1751

I am using workbox to cache my app shell. The network tab shows that the requests are coming from serviceWorker, and assets are definitely cached as they are retrieved in a snap, even on offline mode:

network tab

However, the cache storage tab is always empty:

Cache storage empty

I have attempted to request the same assets via console:

const request = new Request('https://d198jdpljt0zhj.cloudfront.net/assets/bundles/vendor-0332fe450952d0d66900.js', {mode: 'no-cors'});
fetch(request).then(response => console.log(response));

And voila, asset is shown:

cache added

I'm afraid I'm missing something fundamental.

By the way, cache storage is shown correctly in my local environment, so I suspect this is an issue with assets coming from CDN.

1 Answers

This is almost certainly because your CDN doesn't support CORS, and only some strategies cache opaque responses by default.

You can override this with

workbox.routing.registerRoute(
  new RegExp('^https://third-party.example.com/assets/'), 
  workbox.strategies.cacheFirst({
    cacheName: 'assets-cache',
    cacheableResponse: {
      statuses: [0, 200], // Make sure 0 is included in this list.
    }
  })
);

There is logging about this in v2 of Workbox, but only if you specifically have it enabled.

In the upcoming v3 release, we're much more aggressive about logging this, as it is a frequent source of frustration.

This draft of a section of the Workbox v3 docs goes into more detail.

Related