Add this code to registerServiceWorker.js. It will reload the page once a new service worker is activated. I usually add it inside the registerValidSW function as shown below:
function registerValidSW(swUrl) {
//Reload once the new service worker is activated.
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange',
function () {
if (refreshing) return;
refreshing = true;
window.location.reload();
}
);
//Below code is create-react-app default
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
// window.location.reload(true);
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
I noticed that with create-react-app, often successive builds ended up with the same hashed file name. This was causing the app to reuse the old cached files.
To resolve, I rename the old build directory to 'build.old' and then run a fresh build. This way there is a very slim chance that the build will reuse an old file name.
Once build is done, add the below link to service-worker.js:
self.skipWaiting();
This will force the new service worker to be activated even while the existing one is still running.
Add Below headers to both your index.html & service-worker.js:
cache-control: max-age=0,no-cache,no-store,must-revalidate