My (bad) experience with service worker

Matteo Collina
2 min readSep 9, 2020

--

On bugsnag I found many errors regarding old code, no longer present in production.

The problem I found is that some users had the old index.js (the first executed js file), which imported the old serviceWorker, so the ‘unregister’ method was never called.

These are some tests that I’ve done:

- Delete serviceWorker.js

The problem exists, the browser doesn’t notice that the file has been deleted and therefore goes to load old files.

it doesn’t work :(

- Code of my service worker wasn’t changed after build

I had forgotten to add the production NODE_ENV variable to my build script in my package.json. If the production variable is not set, then the registerServiceWorker.js will not refresh on new content properly

"scripts": {
...
"build": "cross-env NODE_PATH=src NODE_ENV=production react-scripts build",
}

it doesn’t work :(

- I tried to import only ‘unregister’ method from service-worker instead of import * from serviceWorker.js

P.S. When you unregister, it will take at least one refresh to make it work

it doesn’t work :(

3- I tried to follow this medium:

https://medium.com/@nekrtemplar/self-destroying-serviceworker-73d62921d717 . The author advises to:

“Remove everything about your previous ServiceWorker (registration/uninstallation code, ServiceWorker file)

Create a file with the same name as your previous ServiceWorker and put it in the same place where your previous ServiceWorker was

Put following code into the file: <Check the link>

it works :)

More:

Here is the life cycle of a service worker: https://developers.google.com/web/fundamentals/primers/service-workers

--

--