score:0

ditch all the other ideas and go for the cra-append-sw. it will save you a lot of time and pain.

it's as simple as installing the package, creating the service worker file in your main folder, and modifying your start and build commands in package.json file like this:

"start": "cra-append-sw --mode dev --env ./.env ./custom-sw.js && react-scripts start",
"build": "cra-append-sw --env ./.env ./custom-sw.js && react-scripts build",

and then you make sure to register the separate service worker in dev mode:

if ('serviceworker' in navigator) {
  console.log('trying to register custom sw');
  navigator.serviceworker
    .register('./firebase-messaging-sw.js')
    .then(function (registration) {
      console.log('registration successful, scope is:', registration.scope);
    })
    .catch(function (err) {
      console.log('service worker registration failed, error:', err);
    });
}

if like me you need access to environment variables in the service worker to initialize the firebase messaging module, this is the only simple option that doesn't require ejecting cra.


i decided to post this answer because i myself overlooked the comments on the other answer and lost time unnecessarily looking for this solution.

score:2

if you would prefer disable the built in service-worker prior to your initial production deployment, then remove the call to serviceworkerregistration.register() from src/index.js and add your own service worker.

if your site/app has already been in production then swap it out for serviceworkerregistration.unregister(). after the user visits your page that has serviceworkerregistration.unregister(), the service worker will be uninstalled and it might take up to 24 hours for the cache to be invalidated (depending on how the service worker is served)

the other option would be to eject and configure their built in solution.


Related Query

More Query from same tag