{"canonical_url":"https://engineer.company/glossary/service-worker/","content_markdown":"# Service worker\n\n## What it is\n\nA service worker is a script that a site registers with the browser, which runs\nit apart from any page and routes the network requests of the pages it controls\nthrough it. Service workers are a kind of web worker: each runs on a thread of\nits own, with no document and no window. The browser starts one when there is\nsomething for it to handle and may stop it as soon as nothing is left, so\nanything it keeps in a variable can be gone by the next event.\n\nA page installs one with a single call, and the specification puts three\nconditions on it. The page must be a secure context, which in practice means\nHTTPS, with `localhost` and the loopback addresses allowed for development. The\nscript must come from the page's own origin, so it cannot live on a CDN,\nalthough it may import code from one. And the registration covers a scope: by\ndefault the folder the script sits in, and nothing wider unless the server sends\na `Service-Worker-Allowed` header with the script.\n\n```js\n// on the page\nnavigator.serviceWorker.register(\"/sw.js\");\n\n// in /sw.js\nasync function answer(request) {\n    const copy = await caches.match(request);\n    return copy ?? fetch(request);\n}\n\nself.addEventListener(\"fetch\", (event) =\u003e {\n    event.respondWith(answer(event.request));\n});\n```\n\nThat worker answers each request from its own copy when it holds one and from\nthe network otherwise. Putting the copies there is the lifecycle's job. Once the\nscript has been fetched, the browser fires `install`, the moment to download and\nstore what the worker will need; if a promise handed to `event.waitUntil()`\nthere rejects, the installation fails. Then `activate` fires, the moment to\nclear out what an older version left behind, and only after that does the worker\nreceive `fetch` events. A page is matched to its worker when it loads, so the\npage that registered the first worker carries on without one until it is\nreloaded, unless the worker calls `clients.claim()`.\n\nThe copies live in Cache Storage, which the same specification defines: named\ncaches of request and response pairs that the worker fills, reads and deletes\nitself. They are separate from the browser's HTTP cache. An entry never expires,\nnever refreshes on its own and survives an update of the worker script, so it\nstays until the worker deletes it or the browser clears the site's storage.\n\n## Why it matters\n\nService workers give a site explicit control over how it keeps working with no\nnetwork at all. A service worker decides request by request, in code the site\nwrote, whether to answer from the network, from its own copies or from both,\nwhich is what makes an installed web app usable on a ship or in a basement. Push\nmessages reach it too, when no page of the site is open.\n\nMost workers come down to choosing a strategy per kind of request, and Workbox,\na library for writing them, names five. Cache first answers from the copy and\ngoes to the network only when there is none, which suits files that never change\nunder the same name. Network first asks the network and falls back to the copy,\nwhich suits pages. Stale-while-revalidate answers from the copy and refreshes it\nin the background. Network only and cache only are the two extremes.\n\nIt is also code that stands between every page in its scope and the network, on\nthe reader's device, and it outlives the visit: a mistake in it stays until a\ncorrected script replaces it. The specification is built around that risk. Every\nnavigation makes the browser check for a new script, and other events do so once\na day has passed since the last check. By default the main script is revalidated\nwith the server rather than taken from the HTTP cache, so a long `max-age` on\nthe worker file cannot keep a broken version in place; imported scripts get the\nsame treatment once a day has passed, or always when `updateViaCache` is `none`.\nThe browser compares the fetched script with the installed one byte for byte,\nand only a difference starts an update. A shift-reload skips the worker for that\none navigation, which is why a bug can look fixed on a developer's machine.\n\nThe waiting rule is the other half of that design. A new version installs\nalongside the old one and then waits, unused, until no open page still depends\non the old one, so two versions never serve one page between them. Calling\n`skipWaiting()` lets it take over at once, at the price of running new code\nunder pages the old one loaded.\n\nStorage is the last cost. Cache Storage counts against the space the site holds\non the reader's device, and under the Storage Standard that space is best-effort\nby default: the browser may clear it when the device runs short, unless the site\nhas asked for persistent storage and been granted it.\n\n## What it looks like in practice\n\nThe case for one is clearest where the network is weakest.\n[The progressive web app built for seafarers and field staff](/portfolio/delivered-full-progressive-web-app-support/)\nserves people who are often offline or on a poor connection. Its service worker\nis set up through the next-pwa plugin, and Workbox runtime caching applies cache\nfirst to what does not change from one request to the next, fonts, images,\naudio, video and CDN assets, alongside HTTP cache-control headers. Because\nservice workers only really behave over HTTPS, the offline and install behaviour\nwas tested over HTTPS on real devices, and repeat loads come back from the cache\ninstead of the network.\n\nThis site makes the opposite choice, and says so. [The cookies page](/cookies/) states\nthat it has no service worker, no IndexedDB and no Cache Storage: nothing from the site\nruns in the background before a reader opens it or after they close it. Its pages ship\nno executable JavaScript. The search code is retained but disabled and does not register\na worker.\n\n[The install page](/install/) draws the consequence for anyone who adds the site\nto a home screen: installation gives it its own window without creating a\nmanaged offline copy. This site ships no service worker or script-managed\noffline storage, so the installed app needs a connection for normal use.\n\nA worker is registered from executable script, which this site's Content-Security-Policy\nnow forbids with `script-src 'none'` on every page. JSON-LD remains inert data. An\nearlier head-template comment recorded a build where 550 of 793 documents stated\n`'none'` and 243 stated `'self'`, matching the pages that carried the list filter then.\nThose figures describe the earlier script-enabled build, not the current policy.\n\n## Where it goes wrong\n\n**The old version keeps serving after a deploy.** The new worker installs and\nthen waits while any open tab still uses the old one, so a reader who never\ncloses that tab keeps running the old code. Call `skipWaiting()` when the new\nversion is safe under pages the old one loaded, or show an update notice and\nhave the page message the waiting worker to call it.\n\n**Pages stay at an old version for weeks.** A cache-first strategy applied to\nHTML answers every navigation from Cache Storage, whose entries never expire and\npay no attention to the server's cache headers. Keep cache first for files whose\nnames change when their contents do, and use network first for pages.\n\n**The install fails and the old worker stays.** One address in the install\nstep's list answers with an error, so `cache.addAll()` rejects, the promise\npassed to `waitUntil()` rejects with it, and the new version is discarded. Build\nthat list from files that exist, and fetch optional files later rather than at\ninstall.\n\n**The worker ignores most of the site.** A script served from `/js/sw.js` has\n`/js/` as both its default and its widest scope, so pages outside that folder\nload without it. Serve the script from the root of the site, or send\n`Service-Worker-Allowed: /` with it.\n\n**Storage on the device grows with every release.** Caches survive an update of\nthe worker script, so each version that opens a cache under a new name leaves\nthe previous one behind. Put a version in every cache name, and in the\n`activate` handler delete each cache the current version does not use.\n\n## Further reading\n\n- [Service Workers](https://www.w3.org/TR/service-workers/) — registration,\n  scope, the update check, the lifecycle and Cache Storage.\n- [Secure Contexts](https://www.w3.org/TR/secure-contexts/) — which origins\n  count as potentially trustworthy, `localhost` and the loopback addresses\n  included.\n- [Fetch Standard](https://fetch.spec.whatwg.org/) — the `Request` and\n  `Response` objects a `fetch` handler receives and returns, and how a request\n  is handed to a service worker.\n- [Storage Standard](https://storage.spec.whatwg.org/) — the storage buckets\n  Cache Storage lives in, quota estimates and how a site asks for persistent\n  storage.\n- [Workbox: workbox-strategies](https://developer.chrome.com/docs/workbox/modules/workbox-strategies)\n  — the five caching strategies and the kind of request each one suits.\n\n\u003chttps://engineer.company/glossary/service-worker/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"How a service worker sits between a site and the network, why a new version waits before it takes over, and where its caches go stale.","formats":{"gemtext":"https://engineer.company/glossary/service-worker/index.gmi","gopher":"https://engineer.company/glossary/service-worker/gophermap","html":"https://engineer.company/glossary/service-worker/","json":"https://engineer.company/glossary/service-worker/index.json","markdown":"https://engineer.company/glossary/service-worker/index.md","pdf":"https://engineer.company/glossary/service-worker/index.pdf"},"kind":"page","language":"en","title":"What is a service worker?","url":"https://engineer.company/glossary/service-worker/","version":1}