Introduction
I was working on one of my Nuxt projects and noticed that some users were using old versions, which was causing some errors to pop up.
I investigated and learned that sometimes PWAs don't update if the user doesn't manually refresh the website. So...
Let's learn how to automatically update to the latest PWA version.
Before we start
This is a simple tutorial for projects with Nuxt and the PWA module, nothing else is required.
Requirements
- Nuxt
- Nuxt PWA module
Create a new plugin
To start, you will need to go to your plugins directory and create a new JavaScript file. I will name it pwa-update.js
but feel free to use whatever you want to.
// pwa-update.js
export default async (context) => {
const workbox = await window.$workbox;
if (!workbox) {
console.debug("Workbox couldn't be loaded.");
return;
}
workbox.addEventListener('installed', (event) => {
if (!event.isUpdate) {
console.debug('The PWA is on the latest version.');
return;
}
console.debug('There is an update for the PWA, reloading...');
window.location.reload();
});
};
Add the plugin to the Nuxt config
Then we have to add it to the plugins array on nuxt.config.js
.
// nuxt.config.js
// ...
plugins: [
{ src: '~/plugins/pwa-update.js', mode: 'client' },
],
// ...
End
And that was it. Easy right?
Self-promotion
If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰
Or support me financially. 💸
Conclusion
Congratulations, today you have set up automatic PWA updates for your project.
Let me know if this tutorial was useful to you in the comments!
Top comments (7)
Hello. This is my PWA section in nuxt.config.js
Your configuration seems fine, and it is working for my users so I don't know what is happening :(
I am not sure if I understand it right. So if I make a new build on the server and user have old version open in the browser, this plugin will detect new version and automatically update refresh the page?
I am not able to test it on localhost cause it refresh the page automatically. Is it possble to test it on localhost? If I add this lines at the beginning of the plugin
else {
console.log('Workbox has been loaded.');
}
I dont see any log in console.
Yes, once the new version is published on the server, when a user loads your website it will reload automatically without the users needing to click the reload button, or implementing a update button on your website.
As far as I know, workers don't execute on localhost, so you cant test it.
@alejandroakbal What do you mean by 'when a user loads your website'? I thought that the use case for this is that the site is already loaded and in the background the code realises that a newer version is available and forces the browser to refresh.
I made this plugin in my project, but it constantly cyclically reloads the page
Weird, could you post the pwa section on nuxt config?