DEV Community

Flawless and Silent Upgrade of the Service Worker 🔌

a-tonchev on April 06, 2021

As many of you already know, the upgrading of the service worker gives us agony. Until now we always need to make some compromises. But what if I...
Collapse
 
brydom profile image
Brydon McCluskey

Hey, I have a quick question regarding this bit:

And NEVER forget to change it when generating every new service worker

Should the REACT_APP_VERSION_UNIQUE_STRING only change when making changes to the service worker, or upon every build and deploy?

Collapse
 
atonchev profile image
a-tonchev

It should be on every build and deploy. Since on every build and deploy you have new files. But you can make it automated - add Date String prefix, suffix etc...

Collapse
 
brydom profile image
Brydon McCluskey • Edited

Thank you!

If anyone is interested, I've edited this script found on SO to replace my "build": "craco build" command in package.json:

const execSync = require("child_process").execSync;

const env = Object.create(process.env);
const generateId = () => Math.random().toString(36).substr(2, 9);

env.REACT_APP_VERSION_UNIQUE_STRING = `${generateId()}-${generateId()}-${generateId()}`;

console.log("Used env variables: " + JSON.stringify(env));
console.log("Run command: 'craco build'");

execSync("craco build", { env: env, stdio: "inherit" });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
asdev808 profile image
asdev808

I have just upgraded from react 16 to 17 and then followed this tutorial, but I still need to close the tab and open again to see the updates, I really hate PWA's.

Collapse
 
atonchev profile image
a-tonchev

Hi @myfairshare the update does not happen immediately. First you need to load the page, so that it detects the new service worker, to prepare caches and to replace the index.html

After the next reload your website will be updated with the new service worker

Collapse
 
asdev808 profile image
asdev808

Ok thanks for the reply mate. I think next time I build a mobile app I will try flutter instead!!

Thread Thread
 
atonchev profile image
a-tonchev

Unfortunately there is a big difference and use cases between PWA and Mobile App. And PWA gain much on popularity. I also hate the way the PWA handles the updates, but they will surely change it in future.

Thread Thread
 
asdev808 profile image
asdev808

I hope your right, thanks!!

Collapse
 
asdev808 profile image
asdev808

Thanks Anton, going to try this, certainly is painful dealing with service workers.

Collapse
 
dannymoerkerke profile image
Danny Moerkerke

If I understand correctly, the only time a new service worker will be activated immediately is when there is only one tab open, correct?

Collapse
 
atonchev profile image
a-tonchev

Yes