DEV Community

Cover image for Updating Service Workers in Production
Vinicius Blazius Goulart
Vinicius Blazius Goulart

Posted on • Edited on

Updating Service Workers in Production

Service Workers are powerful tools within web browsers that enable a plethora of offline operations, including caching, real-time notifications, geolocation handling, and more exciting features. However, due to their separation from web applications and their role as proxy servers between connections, dealing with them in production can be quite challenging, especially when it comes to managing browser caches.

How to Update a Service Worker in Production?

There are several reasons why you might need to update a service worker in production. Consider a scenario where you want to change the path of your service worker. You previously had a service worker that only worked within the login path of your application, but now you want it to function globally.

In such cases, it's crucial to ensure that two services aren't running concurrently on the same routes, to avoid operational duplication. To address this, you can execute the following code in the entry point of your application:

if ('serviceWorker' in navigator) {
    const registrations = await navigator.serviceWorker.getRegistrations();

    const oldSw = registrations.find((registration) =>
      registration.active?.scriptURL.includes('/login/sw.js'),
    );

    if (oldSw) {
      oldSw.unregister();
    }

    navigator.serviceWorker.register('/sw.js');
}
Enter fullscreen mode Exit fullscreen mode

With this code, you can identify a service worker running on a specific path, unregister it, and then re-register it with the desired path. This ensures that the service worker previously registered under /login is no longer active and allows the one registered under / to handle all the tasks.

Ensuring All Users Have the Updated Version

You can also ensure that browsers update all service workers without waiting for the entire application to restart:

self.addEventListener('install', (event) => {
  event.waitUntil(self.skipWaiting());
});
Enter fullscreen mode Exit fullscreen mode

However, this action is not always recommended. It's best to wait for the complete service worker lifecycle to occur correctly. Use this approach only if your change won't result in a breaking change for the client, and avoid using it for significant changes.

Updating service workers in production requires careful planning and consideration of how changes might impact user experience. By following these best practices, you can efficiently manage service worker updates and enhance the performance and reliability of your web applications.


Photo by Joshua Rawson-Harris on Unsplash

Top comments (0)