I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce.
Failed to update a ServiceWorker for scope ('https://myapp.com/') with script ('https://myapp.com/service-worker.js'): A bad HTTP response code (400) was received when fetching the script.
Surprisingly, when I visit the URL mentioned in the error message, the service worker JS file loads perfectly fine.
In delving into my vue.config.js file, I found the following configuration:
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: './src/sw.js',
swDest: 'service-worker.js',
},
},
This is how my src/sw.js
file looks like:
/* eslint-disable */
// This piece of code is crucial for listening to the user's confirmation to update the app.
self.addEventListener('message', e => {
if (!e.data) {
return;
}
switch (e.data) {
case 'skipWaiting':
self.skipWaiting();
break;
default:
// NOOP
break;
}
});
workbox.core.clientsClaim(); // For Vue CLI 4 and Workbox v4
// Precaching code provided by Workbox.
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
Regarding the src/registerServiceWorker.ts
file:
import { register } from 'register-service-worker';
if (process.env.NODE_ENV !== 'development') {
register(`${process.env.BASE_URL}service-worker.js`, {
registered(registration) {
// Check for code updates every minute
setInterval(() => {
registration.update();
}, 1000 * 60);
},
updated(registration) {
document.dispatchEvent(
new CustomEvent('swUpdated', { detail: registration })
);
},
});
}