Service Worker Lifecycle: Install, Activate and Fetch
Understand the service worker lifecycle: register, install, waiting, activate, fetch, skipWaiting, clients.claim, updates and the debugging traps.

A service worker is a script that the browser runs in the background, separate from any page, and that can intercept every network request from the pages it controls. That makes offline apps, instant repeat loads, push messages and background sync possible. It also makes service workers the part of the web platform that causes the most confusion, because a worker has its own lifecycle with several states, it does not take over pages the moment it is installed, and an old version can keep running while a new one waits. This post walks through the lifecycle in order: registration, the install event, the waiting state, the activate event, handling fetches, how updates happen, when to use skipWaiting() and clients.claim() and which mistakes make developers think the worker is broken. The reference is the Service Workers specification and the MDN Service Worker API guide. Service workers need a secure context, which means HTTPS, with localhost allowed for development.
Registering
A page registers a worker script with navigator.serviceWorker.register(). The call returns a promise for a registration.
if ("serviceWorker" in navigator) {
window.addEventListener("load", async () => {
try {
const registration = await navigator.serviceWorker.register("/sw.js");
console.log("scope", registration.scope);
} catch (error) {
console.log("registration failed", error.name);
}
});
}scope https://example.com/The registration happens after the load event, so that it does not compete with the page's own resources. The scope decides which pages the worker controls: by default it is the folder of the script, so /sw.js controls the whole site and /app/sw.js controls only paths under /app/. A worker cannot control a wider scope than its script's location, unless the server sends a Service-Worker-Allowed header. Registering the same script again is harmless: the browser compares and does nothing if it is unchanged.
The states
A worker moves through states that you can read from worker.state.
| State | Meaning |
|---|---|
installing | The install event is running |
installed | Installed, and waiting to take over (often called waiting) |
activating | The activate event is running |
activated | Ready to handle events such as fetch |
redundant | Replaced, or failed to install |
A registration has three slots, installing, waiting and active, which show where each worker version is. There can be an active worker, a waiting worker and an installing worker at once, for different versions of the script.
const registration = await navigator.serviceWorker.ready;
console.log(registration.active?.state);
console.log(registration.waiting?.state);
console.log(registration.installing?.state);activated
undefined
undefinedThe values show the stable situation, with one active worker and nothing else. During an update, the new worker appears in installing and then waiting.
The install event
The install event fires once for each new version of the script. It is the place to pre-cache the files that the app needs offline, and event.waitUntil() tells the browser to wait for a promise before treating the install as finished. If the promise rejects, the install fails and the worker becomes redundant.
const CACHE = "shell-v3";
const ASSETS = ["/", "/app.css", "/app.js", "/offline.html"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(ASSETS)));
});(first visit) the four files are fetched and stored in the cache "shell-v3"cache.addAll fails as a whole if one request fails, which makes the install fail, so keep the list small and make sure every URL exists. Do not fetch from the network in a way that depends on the user being online later. See the Cache API for the storage side.
Waiting
After a successful install, a new worker does not take over at once if an older one is running and controls pages. It waits until every page controlled by the old worker is closed, to avoid two versions of the app running with different cached files. This is the cause of the common complaint: "I deployed an update, and users still see the old version". The old page must be closed, not just reloaded, because a reload keeps the same worker until the new page is loaded and the old one is gone, and in many browsers a reload in the same tab is enough, while a second open tab keeps the old worker alive.
The activate event
When the worker becomes active, the activate event fires. Use it to clean up what older versions left behind, since the old worker is gone, which is the safest moment to delete its caches.
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((names) =>
Promise.all(names.filter((name) => name !== CACHE).map((name) => caches.delete(name))),
),
);
});(after an update from shell-v2 to shell-v3) the cache "shell-v2" is deletedDoing the cleanup in install would break the old version while it is still serving pages, so always do it in activate.
The fetch event
Once active, the worker receives a fetch event for each request from pages it controls, and for requests the page's resources make. event.respondWith() supplies a response, and not calling it lets the request go to the network as usual.
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request).catch(() => {
if (request.mode === "navigate") return caches.match("/offline.html");
return Response.error();
});
}),
);
});(online, file cached) served from the cache
(offline, page navigation) the offline page is shown
(offline, an uncached image) a network error responseThe handler must call respondWith synchronously, during the event, with a promise for the response. Calling it later throws an InvalidStateError. Skip requests that you do not want to handle, such as non-GET requests and cross-origin analytics calls, by returning without calling respondWith.
Taking control: skipWaiting and clients.claim
Two methods change the normal pace. self.skipWaiting(), usually called in install, makes the new worker skip the waiting state and activate at once. clients.claim(), called in activate, makes the worker control the pages that are already open, which otherwise are controlled by no worker until the next navigation, in the case of a first install.
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
});(new version installed) it activates immediately and controls all open tabsThe danger is that a page loaded with the old files may now talk to a worker with new ones, and an API or a cached asset can mismatch. That is acceptable for sites whose cache entries are self-contained, and risky for a single-page app that loads many files over time. The safer pattern is to let the page decide: when registration.waiting appears, show a message such as "A new version is available", and when the user agrees, post a message to the waiting worker, which calls skipWaiting(), then reload on the controllerchange event.
const registration = await navigator.serviceWorker.register("/sw.js");
registration.addEventListener("updatefound", () => {
const worker = registration.installing;
worker.addEventListener("statechange", () => {
if (worker.state === "installed" && navigator.serviceWorker.controller) {
showUpdateBanner(() => worker.postMessage({ type: "SKIP_WAITING" }));
}
});
});
navigator.serviceWorker.addEventListener("controllerchange", () => location.reload());self.addEventListener("message", (event) => {
if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});(new version ready) a banner appears; on "Update" the page reloads with the new worker in controlThe check on navigator.serviceWorker.controller separates the first install, where nothing needs to reload, from an update.
How updates are found
The browser checks for a new version when the user navigates to a page in scope, and at most once every 24 hours otherwise, by fetching the script and comparing it byte by byte with the stored one. Any difference starts a new install. It also compares imported scripts. You can trigger a check with registration.update(). The browser bypasses the HTTP cache for the worker script by default in current versions, with updateViaCache: "imports" as the default, so a long cache lifetime on sw.js does not delay updates, though serving it with Cache-Control: no-cache is a safe habit. Because the script is compared by bytes, a worker that never changes never updates, so embed a version string or a build hash in it to force a new install when your assets change.
Lifetime of a running worker
A worker is not always running. The browser starts it for an event and stops it after a short idle period, and all variables in its global scope are lost. Do not keep state in global variables: store it in the Cache API, IndexedDB or the pages. Long work needs event.waitUntil() to keep the worker alive, and even then the browser limits how long. Register event listeners at the top level of the script, synchronously, since listeners added later, inside a promise, may be missed when the worker starts for an event.
Debugging traps
The browser's developer tools have an Application panel, with a Service Workers section that shows the states, a "Update on reload" checkbox, a "Bypass for network" option and a button to unregister, and the Cache storage view. Use them. Common traps are testing in a normal tab with an old worker still active, which hides your changes; the "Update on reload" option fixes it in development. Using the wrong scope, for example a script in /static/sw.js that cannot control /. Serving the script with a wrong MIME type, since it must be a JavaScript type. Hitting a redirect on the script URL, which is not allowed. And caching index.html forever with cache-first, which traps users on an old version: serve navigations with network-first or stale-while-revalidate. A way out is to ship a worker that unregisters itself and clears caches, with registration.unregister(), so you should keep that option in mind from the start.


