Automatically Generate A New Service Worker Version

The rule of thumb with service workers is that a new one will install if there is a byte-difference compared to the one the browser already has installed.

The best way to trigger a new service worker install is if you make a slight modification to your existing service worker file (sw.js) such as the CACHE_NAME (refer to the service worker example below).

Service Worker Example

Usually, people will have a version number like v-1 and increment it each time v-2, v-3, etc. But that is tedious and repetitive, so I wrote an automated node script which updates the version name to the latest timestamp.

The Magic Stick Script

Below is a node script you can integrate into your build job to autogenerate the CACHE_NAME within the service worker.

Make the file executable using the following command:

chmod +x generate-new-service-worker-version.js

Then run the script with node like so:

node generate-new-service-worker-version.js

I hope you found this script super useful and get as much benefit out of it as I did. Cheers.