How to Delete a Service Worker

Surprisingly, if you want to completely remove a service worker from a website, you need more than deleting the file on your server. Explanations below.

2 min read
How to Delete a Service Worker
Photo by cottonbro from Pexels.

When I decided to make full use Ghost as my CMS (Content Management System), I had to reimplement some features that I previously programmed. As I wanted to quickly ship this new version into production, I chose to skip some features that I might add again in the future. One of these features was that my website was a Progressive Web App (better known as a PWA).

PWA uses Service Workers, a small JavaScript file that provides certain features like an offline experience to users. Unfortunately for me, the service worker is cached by the browser and if I deleted that file, the service workers installed on my visitors' browsers would not be updated because the file would result in a 404 error page.

Since I didn't want to ask my visitors to manually clear site data, I had to find a way to delete it programmatically. 🤖

Fortunately, I knew there was a way to remove it using a self-destructing service worker. 🧨

Simply replace your service-worker.js (or sw.js) file and the next time a user visits your website, the service worker on its navigator will self-destruct! 💥

// Inspired from https://github.com/NekR/self-destroying-sw
self.addEventListener("install", (event) => {
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  self.registration
    .unregister()
    .then(() => self.clients.matchAll())
    .then((clients) => {
      clients.forEach((client) => {
        if (client.url && "navigate" in client) {
          client.navigate(client.url);
        }
      });
    });
});
The code that will replace our service worker code.

A useful snippet to keep on hand if you play with service workers! 🤩

And if your want to know more about removing old services workers, Chrome Developers has a great article on that:

Removing buggy service workers - Chrome Developers
How to fix a service worker that is causing problems.

Have fun playing with service workers! 🤗