How to show a message that a new app version available even if users don't reload the app

868 Views Asked by At

I have a Next.js app that uses next-pwa library for setting app the service worker. After having deployed a new version I want to show a snackbar that it is available.

Currently, it does show up when I reload the app but it seems pretty useless then because the codebase is already up to date after reloading.

I wonder if it is possible to show that snackbar when a user left the tab open for a while, a new version had been deployed, and then they came back and see the snackbar?

My code currently looks something like this:

const useServiceWorker = () => {
  const { showSnackbar } = useSnackbars()

  useEffect(() => {
    if (window !== 'undefined' && 'serviceWorker' in navigator && window.workbox !== undefined) {
      const wb = window.workbox

      wb.addEventListener('waiting', () => {
        showSnackbar('A newer version of the app is available!', {
          onClick: () => {
            wb.addEventListener('controlling', () => window.location.reload())
            wb.messageSkipWaiting()
          },
          onClose: () => {
            // do smth else
          },
        })
      })

      wb.register()
    }
  }, [])
}
1

There are 1 best solutions below

0
On

I wonder if it is possible to show that snackbar when a user left the tab open for a while, a new version had been deployed, and then they came back and see the snackbar?

You can call wb.update() to check for service worker updates. If there is one, it will install it, like wb.register() does. You could use setInterval to call it at regular intervals.

Currently, it does show up when I reload the app but it seems pretty useless then because the codebase is already up to date after reloading.

It needs two reloads to fully update. The first runs wb.register() again when the component is mounted, which installs the service worker. Once installed, the 'waiting' event gets triggered, which shows the snackbar. It's not useless at all because you're still running on the old service worker. It takes the combination of skipWaiting (to activate the new service worker) and window.location.reload() (to update the page) to have a completely up-to-date app.

That said, the first time you deploy the snackbar, your users will need to update the hard way, by closing all clients and reopening the app.