DEV Community

loading...
Cover image for How to detect and update to the latest version with Nuxt PWA

How to detect and update to the latest version with Nuxt PWA

alejandroakbal profile image Alejandro Akbal Originally published at blog.akbal.dev ・2 min read

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();
  });
};
Enter fullscreen mode Exit fullscreen mode

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' },
  ],

// ...
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (4)

Collapse
deprime profile image
Andrey Dyugaev

Hello. This is my PWA section in nuxt.config.js

pwa: {
    meta: {
      title: 'Ullanor',
      author: 'Deprime',
    },
    manifest: {
      name: 'Ullanor mobile browser strategy',
      short_name: 'Ullanor',
      lang: 'ru',
    },
  },
Enter fullscreen mode Exit fullscreen mode
Collapse
alejandroakbal profile image
Alejandro Akbal Author

Your configuration seems fine, and it is working for my users so I don't know what is happening :(

Collapse
deprime profile image
Andrey Dyugaev

I made this plugin in my project, but it constantly cyclically reloads the page

Collapse
alejandroakbal profile image
Alejandro Akbal Author

Weird, could you post the pwa section on nuxt config?

Forem Open with the Forem app