DEV Community

Dmitri Pisarev πŸ‡·πŸ‡Ί
Dmitri Pisarev πŸ‡·πŸ‡Ί

Posted on

Getting a PWA to self-update

So people have asked me to share how to make sure your PWA automatically updates itself, even on #iOS 12 (which preserves the state of your app even when quitting it).

In my case the app is stateless so I can allow myself to just reload the app without showing any prompts for update to the user. If your app is more complex you can show a prompt in every place I do location.reload, all other things should be relevant.

Here's the point to listen if the new ServiceWorker is available: https://github.com/dimaip/calendar/blob/ea68923793e8975a483aff8605f52e5c913b9344/app/serviceWorker.js#L26

When installing SW I do skipWaiting to make it take control immediately, without waiting for all tabs to be closed. Also I do clients.claim in order to take control of all the tabs that have no SW installed yet for some reason: https://github.com/dimaip/calendar/blob/ea68923793e8975a483aff8605f52e5c913b9344/app/service-worker.js#L6-L11

On every route transition I compare the current app's version with the version returned by app's version endpoint: https://github.com/psmb/calendar/blob/ea68923793e8975a483aff8605f52e5c913b9344/app/Routes.js#L24
If the versions differ I reload. This is especially important on iOS 12 where there's no way to make the app to reload from user actions.

On every deploy I tag a new version with yarn version --patch. Here's how I expose it server-side: https://github.com/psmb/calendar/blob/ea68923793e8975a483aff8605f52e5c913b9344/server.js#L73

I also display the version in the app, quite helpful when debugging: https://github.com/psmb/calendar/blob/ea68923793e8975a483aff8605f52e5c913b9344/app/containers/Main/BurgerMenu.js#L87

That's it! On every route transition I can be sure that the users have the latest version of the app.

Make sure you also read this related post how to deploy an app with code-splitting, or else you won't get very far with auto-updates! https://dev.to/dimaip/what-you-should-consider-before-deploying-an-app-with-code-splitting-1n76

Top comments (0)