Full answer
A service worker is a special kind of worker registered by a page with navigator.serviceWorker.register('/sw.js'). It runs in a separate context with no DOM, lives by events, and can be stopped and restarted by the browser at any time, so it must not keep state in variables. It works only on secure origins (HTTPS, with localhost allowed for development), and it controls pages within its scope.
Lifecycle: after registration, the browser downloads the script and fires install. This is where a site pre-caches its core files, with event.waitUntil(...) to keep the worker alive until the work is done. A new worker then waits while an older version still controls open pages, unless the script calls self.skipWaiting(). When it takes over, activate fires, which is the place to delete old caches, and clients.claim() lets it control open pages immediately. The browser checks for a changed sw.js file on navigation, at least every 24 hours, and a byte change starts the update.
The fetch event is the core. The handler calls event.respondWith(promise) to answer a request itself. Common strategies:
- Cache first: answer from the cache and go to the network only on a miss. It suits versioned static files that never change.
- Network first: try the network, and fall back to the cache when offline. It suits pages and API data that should be fresh when possible.
- Stale-while-revalidate: answer from the cache immediately and fetch a fresh copy in the background for next time. It suits content where speed matters more than freshness.
- Network only and cache only for special cases.
Risks: a faulty worker can serve broken pages for a long time, so versioned cache names and a tested update path matter. Do not cache responses that depend on a user's login without care, and never cache error responses by mistake.
The same pattern is also the base for push notifications and background sync.
// The strategies are written as plain functions that take a cache and a fetch function.
// In a real service worker, cache comes from caches.open(name) and fetchFn is fetch.
class MemoryCache {
#store = new Map();
async match(request) {
const stored = this.#store.get(request.url);
return stored ? stored.clone() : undefined;
}
async put(request, response) {
this.#store.set(request.url, response.clone());
}
}
const log = [];
let version = 1;
const network = async (request) => {
log.push(`network hit for ${new URL(request.url).pathname} (v${version})`);
return new Response(`content v${version}`);
};
async function cacheFirst(request, cache, fetchFn) {
const cached = await cache.match(request);
if (cached) return cached;
const fresh = await fetchFn(request);
await cache.put(request, fresh.clone());
return fresh;
}
async function networkFirst(request, cache, fetchFn) {
try {
const fresh = await fetchFn(request);
await cache.put(request, fresh.clone());
return fresh;
} catch {
const cached = await cache.match(request);
if (cached) return cached;
return new Response('offline', { status: 503 });
}
}
async function staleWhileRevalidate(request, cache, fetchFn) {
const cached = await cache.match(request);
const refresh = fetchFn(request).then((fresh) => cache.put(request, fresh.clone()));
return cached ?? (await refresh, cache.match(request));
}
(async () => {
const request = new Request('https://school.example/app.js');
const cache1 = new MemoryCache();
console.log('cache first:', await (await cacheFirst(request, cache1, network)).text());
version = 2;
console.log('cache first again:', await (await cacheFirst(request, cache1, network)).text());
const cache2 = new MemoryCache();
version = 1;
console.log('network first:', await (await networkFirst(request, cache2, network)).text());
const offline = async () => {
throw new TypeError('Failed to fetch');
};
console.log('network first offline:', await (await networkFirst(request, cache2, offline)).text());
console.log('offline with empty cache:', (await networkFirst(new Request('https://school.example/other'), cache2, offline)).status);
const cache3 = new MemoryCache();
version = 1;
console.log('stale-while-revalidate, first visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
version = 2;
console.log('stale-while-revalidate, next visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
await new Promise((resolve) => setTimeout(resolve, 10));
console.log('stale-while-revalidate, third visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
console.log(log.length, 'network calls in total');
})();Run with Node.js v24.22.1 as js-91.js; two runs gave identical output. Output: cache first: content v1 cache first again: content v1 network first: content v1 network first offline: content v1 offline with empty cache: 503 stale-while-revalidate, first visit: content v1 stale-while-revalidate, next visit: content v1 stale-while-revalidate, third visit: content v2 5 network calls in total
Key points
- A service worker is an event-driven, DOM-less script between page and network; HTTPS only.
- Lifecycle: install (pre-cache), waiting, activate (clean old caches).
- respondWith in the fetch event lets the worker answer requests.
- Strategies: cache first, network first, stale-while-revalidate.
- Version cache names and plan updates; a bad worker can persist.
Common mistakes
- Keeping state in global variables of the worker, which is lost when the browser stops it.
- Forgetting to version cache names and delete old ones in the activate event.
- Using cache first for HTML pages, which leaves users on stale pages for a long time.
- Not testing the update path, so users get stuck on an old worker.
Follow-ups
- What happens to open tabs when a new service worker is installed, and what does skipWaiting change?
- How would you handle a cached response that depends on the user's login state?
- How do you debug and unregister a service worker during development?
Tips
- Describe the lifecycle in order: register, install, wait, activate, fetch.
- Name the three strategies and the type of content each suits.
- Mention versioned caches and update risk; it shows production experience.