Search code examples
node.jsprogressive-web-appsservice-workeramazon-cloudfrontcdn

PWA Setup with Cloudfront CDN?


My web app has a service worker that was working fine before I added integration with Cloudfront CDN.

I'm registering the service worker on the client like so:

    navigator.serviceWorker
        .register('https://www.my-domain-name.com/sw.js')
        .then(() => console.info('service worker registered.'))
        .catch(error => {
            console.log('Error registering serviceWorker: ', error)
        })

I get this in the client console logs:

enter image description here

And Lighthouse is telling me this:

No matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest.

I've tried multiple URLs when registering the service worker, including:

  • "/sw.js"
  • "https://www.my-domain-name.com/sw.js"
  • "https://###.cloudfront.net/sw.js"

...but so far none have worked.

What am I missing?

UPDATES

I've learned a lot more but still have questions:

  • I got a great answer from @JeffPosnick to my related SO post here. That explained the errors.
  • The URL for "failed to fetch" was the URL specified in my manifest "start_url". But I'm still getting a fetch error here, even outside of Lighthouse testing. Anybody know why?
  • I unchecked the Lighthouse "Clear Storage" checkbox. Now Lighthouse is saying my service worker is working.

enter image description here

Theory: when Lighthouse clears storage it blows away the service worker, explaining why I get a failing PWA score from Lighthouse when "Clear Storage" is checked. Is this theory correct?


Solution

  • Okay, I finally got this all working. In addition to the things I posted in the update to the original post, I also had to find a service worker that would work with React.

    I went with this one.

    Now if the network is offline, and I reload the page, I still see my React home page. Nice!