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()
}
}, [])
}
You can call
wb.update()
to check for service worker updates. If there is one, it will install it, likewb.register()
does. You could usesetInterval
to call it at regular intervals.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 ofskipWaiting
(to activate the new service worker) andwindow.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.