7

According to workbox doc, cross domain request should be configured to ensure that regular expression matches the beginning of the URL. However, it doesn't work.

The service worker code is like below.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');

workbox.routing.registerRoute(
  /.*\.(png|jpg|jpeg|svg|gif)/,
  workbox.strategies.cacheFirst()
);

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst()
);

In the page, responses from same origin resources are cached, but responses from https://a248.e.akami.net is not.

Anything wrong with my config? or is this a workbox 3.0.0 bug?

Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230

1 Answers1

10

Do you have CORS enabled on your https://a248.e.akami.net server? If not, you'll be getting back opaque responses, and by default, those will not be cached when using a cacheFirst strategy.

There's a guide for handling third-party requests with a recipe you could use if you want to opt-in to caching those responses when using a cacheFirst strategy:

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst({
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200]
      })
    ]
  }),
);

You should also see a new warning logged in the JavaScript console when using Workbox v3 in localhost when this situation arises, explaining what's going on.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • Looks like `networkFirst` and `staleWhileRevalidate` strategies (documentation version 6.0.2) state that they cache opaque (that's how the documentation calls responses which don't support CORS) responses as well, so we can use those too? – Csaba Toth Dec 15 '20 at 20:31
  • "By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are cross-origin requests where the response doesn't support CORS." https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-strategies.StaleWhileRevalidate – Csaba Toth Dec 15 '20 at 20:32
  • 1
    Yes, you could use those without having to add in the `CacheableResponsePlugin`. – Jeff Posnick Dec 15 '20 at 20:34