Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Versioning the service worker so a bad cache cannot trap visitors on old code

Versioning the service worker so a bad cache cannot trap visitors on old code A service worker is a strange piece of code. Once a visitor's browser installs it, it keeps running long after they have left my site, and i

Versioning the service worker so a bad cache cannot trap visitors on old code

A service worker is a strange piece of code. Once a visitor's browser installs it, it keeps running long after they have left my site, and it decides what they see next time they come back. That is the whole point of one — it makes the site fast and installable. It is also the whole danger. If I ship a broken version, or even just an old one, the worker can keep serving stale pages for days while I sit there wondering why nobody can see my fix.

I learned this the hard way on ramrom.io, my free video downloader. The early version of my service worker cached aggressively. It did its job too well. After one deploy, a visitor told me the download button was still doing the old thing, even though I had fixed it that morning. The file on the server was new. The file in their browser was not. The service worker had decided the cached copy was good enough.

The problem with an unversioned cache

A service worker cache is just a named box. You open it, you put files in, and later you read them back. The trouble starts when the name never changes. If the cache is always called ramrom-v1, then version two of the site, version three, version ten — they all share the same box. Old files sit next to new ones, and the worker has no way of knowing which are fresh.

Worse, an old worker does not go away just because a new one exists. The browser installs the new worker, but the old one keeps controlling open pages until they are all closed. So a visitor with a tab open from yesterday can be running yesterday's code while I am looking at today's.

The versioned cache

The fix is boring, which is why I like it. The cache name carries a version number, and I bump it on every deploy that changes cached files:

const CACHE_NAME = 'ramrom-v2';

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(
        names
          .filter((name) => name !== CACHE_NAME)
          .map((name) => caches.delete(name))
      )
    )
  );
});

When the new worker activates, it deletes every cache that is not the current one. Old files are gone, not just ignored. That single activate handler is the difference between "the fix is live" and "the fix is live, except for everyone who visited last week".

I also made the fetch handler network-first for pages, cache-first only for static assets that carry a versioned query string, like app.js?v=12. A page should always try the network first and fall back to the cache only when the network fails. A script with ?v=12 in its name is safe to serve from cache, because when I change it, the URL changes too and the old copy is simply never asked for.

Two rules I now follow

First, every deploy that touches a cached file bumps the cache version. It takes five seconds and it is the only thing standing between a fix and a visitor who never sees it. I keep the version in one place at the top of sw.js, so there is no hunting through the file.

Second, the worker never caches a failed response. An early version cached whatever came back, including error pages, which meant a visitor could get a cached 404 served as if it were a real page. Now the fetch handler checks response.ok before putting anything in the box. A broken response is never worth keeping.

What changed for visitors

Nothing visible, which is exactly the point. The site still loads fast, still works offline for pages already visited, and still installs as an app on Android. The difference is invisible: when I ship a fix, visitors actually get it. The download button does what the current code says it does, not what last month's code said.

A service worker is a promise to the browser that you will manage the cache properly. Versioning the cache is how you keep that promise. Without it, the fastest site in the world is just a very efficient way of showing people old mistakes.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.