david_adler
david_adler

Reputation: 10912

Service worker is being cached by workbox

I have the following workbox configuration

config.plugins.push(
    new GenerateSW({
      swDest: 'service-worker.js',
      clientsClaim: true,
      // Only cache PWA version. Excludes pre-rendered AMP pages
      exclude: [/^(?!shell).*index\.html$/],
      // PWA routing ie single page app
      navigateFallback: '/shell/index.html',
      navigateFallbackBlacklist: [
        /*\.js.*/
      ],
    }),
  )

My express server does not cache the service worker

import serve from 'serve-static'

function setHeaders(res: Response, file: string) {
  let cache =
    basename(file) === 'service-worker.js'
      ? 'private,no-cache,no-store,must-revalidate,proxy-revalidate'
      : 'public,max-age=31536000,immutable'
  return res.setHeader('Cache-Control', cache) // don't cache service worker file
}
app.use(serve(BUILD_LOCATION, { setHeaders }))
  1. First access of the page works as expected. The service-worker.js is returned to be the latest version and precaches all assets and the shell.html.
  2. On refresh, as expected, the shell.html is served instead of going to the server and the assets are served from the service worker.
  3. Let's say I rebuild the assets and update service-worker.js.
  4. I expect the new service-worker.js to be loaded from the server and all new assets to be precached.

Instead I see the following the empty response

enter image description here enter image description here enter image description here

And I get the following error in the console The script has an unsupported MIME type ('text/html').

So it looks like the service worker is serving shell/index.html instead of going to the server for service-worker.js. To verify this I accessed view-source:https://localhost/service-worker.js shown below. How can I stop the service worker from caching itself. I thought that's what I was doing with navigateFallbackBlacklist

enter image description here

Upvotes: 0

Views: 630

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

Going to view-source:https://localhost/service-worker.js in a browser will trigger a navigation request for https://localhost/service-worker.js, and then show you the resulting text content of the HTTP response for that navigation request.

That's not how updates to the service worker would normally be fetched—the normal update flow will make a non-navigation request to your server.

If you want an accurate view of the contents of your service-worker.js response, I'd recommend clicking on that request in the Network panel and then going to the "Response" panel of the viewer, like:

Network panel's Response view

Alternatively, you can visit https://localhost/service-worker.js in an Incognito window, and even though that will result in a navigation request, the Incognito window shouldn't have an associated service worker, so that navigation request won't get intercepted.

Upvotes: 1

Related Questions