Search code examples
service-workerprogressive-web-appsworkbox

Service worker and caching images from other domain (aws s3) : "will not cache opaque responses"


I am trying to make a site available offline and to cache images retrieved from AWS S3. I am using the workbox library:

var CACHE_VERSION = '2019-02-03'

// cf https://developers.google.com/web/tools/workbox/guides/get-started
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.6.1/workbox-sw.js')

workbox.routing.registerRoute(
  // Cache image files
  /https:\/\/s3\.amazonaws\.com\/myproject\/img\/.*\.(?:png|jpg|jpeg|svg)/,
  // Use the cache if it's available
  workbox.strategies.cacheFirst({
    // Use a custom cache name
    cacheName: 'image-cache-' + CACHE_VERSION,
    plugins: [
      new workbox.expiration.Plugin({
        // Cache for a maximum of a week
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
)

This results in the following error message from workbox in the console:

The response for 'https://s3.amazonaws.com/myproject/img/icon.png' is an opaque response. The caching strategy that you're using will not cache opaque responses by default.

I have added the crossorigin='anonymous' attribute for those images, and I have this CORS configuration on AWS S3:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

Am I not using CORS properly? How to make the response a normal one and not an opaque one?


Solution

  • Okay this was a stupid mistake. I was doing the right thing, but the crossorigin="anonymous" attribute was set on some of the images and not on the others. Properly setting it on all the images fixes the problem.

    The site I'm working on uses a combination of background images in an unusual way, which made it harder to debug. The image on top properly had the crossorigin attribute, but the other images hidden under it did not have it, and were causing everything to fail, including the display of the image on top, which was properly cached in offline mode. Stupid mistake.