How to make workbox cache cross origin responses?
Asked Answered
G

1

8

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?

Ghiberti answered 15/3, 2018 at 9:32 Comment(0)
A
11

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.

Appliance answered 15/3, 2018 at 20:27 Comment(3)
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?Jenette
"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." developers.google.com/web/tools/workbox/reference-docs/latest/…Jenette
Yes, you could use those without having to add in the CacheableResponsePlugin.Appliance

© 2022 - 2024 — McMap. All rights reserved.