Search code examples
amazon-cloudfrontcreate-react-appgatsbynetlify

Remove service-worker.js (special case)


What I mean by special case is that I need to remove the old service worker when I was using create-react-app. I should have removed it when using cra before switching the whole website to use gatsby. With gatsby I know I can remove service worker like this

 //'gatsby-plugin-offline',
'gatsby-plugin-remove-serviceworker'

But on the user's browser, they visited my website a long time ago when my website was using CRA with service worker installed on their device. And then my stupidity, I didn't remove CRA's service worker before moving to gatsby. So right now, my website is using gatsby which I have configured to remove service worker like the code above. But it doesn't remove CRA's service worker. On gatsby-browser.js I tried this code, but it doesn't work.

export const onClientEntry = async () => {
    if ('serviceWorker' in navigator) {

        navigator.serviceWorker.getRegistrations().then(function(registrations) {

        for(let registration of registrations) {
            console.log('Service Worker registration removed: ');
                registration.unregister()

        }}).catch(function(err) {

            console.log('Service Worker registration failed: ', err);

        });
    }
} 

Related information : My CRA's website used to hosted on AWS, and delivered by cloudfront. Then my website using gatbsy is currently hosted on Netlify and DNS is managed by AWS. I need to host the website on netlify since i'm using netlify cms.


Solution

  • I have found the solution for it. The CRA's service worker won't be unregistered because there is no service-worker.js file with my current gatsby site. So by adding a service-worker.js file in static folder it will work.

    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister();
        });
      }