Service Worker
A service worker is a JavaScript script that a browser runs in the background, separate from a web page, enabling features like offline caching, push notifications, and network request interception that don't require a web page or user…
Definition
A service worker is a JavaScript script that a browser runs in the background, separate from a web page, enabling features like offline caching, push notifications, and network request interception that don't require a web page or user interaction to be active.
Overview
A service worker sits as a programmable proxy between a web app and the network. Once registered by a page, it installs and activates independently of any open tab, then intercepts every fetch request the page makes, letting the app decide whether to serve a response from a local cache, the network, or a combination of both. This is the technical foundation of most offline-capable web apps and Progressive Web Apps: by caching HTML, CSS, JavaScript, and API responses ahead of time, a service worker can keep an app functional even when the network drops. Because it runs on its own thread with no access to the DOM, a service worker communicates with the page through message passing, and it has its own lifecycle — install, activate, and idle/terminate — that developers must design around explicitly, typically using a caching strategy such as cache-first, network-first, or stale-while-revalidate depending on how fresh the content needs to be. It also underpins Web Push notifications and background sync, allowing an app to wake up and process deferred work even when the browser tab is closed. Service workers require HTTPS (localhost is exempted for development) since they have significant power over network traffic, and getting the caching logic wrong is a common source of bugs — stale content sticking around, or updates failing to reach users, are classic service-worker pitfalls. Tools like Lighthouse audit whether a site registers a service worker as part of its Progressive Web App and Core Web Vitals-adjacent checks, and frameworks like React and Next.js offer plugins that generate service worker code automatically rather than requiring it to be hand-written.
Key Concepts
- Runs independently of any open browser tab, on its own background thread
- Intercepts and can rewrite every network request the page makes
- Enables offline-first experiences via programmable caching strategies
- Powers Web Push notifications and background sync
- Has an explicit install/activate/idle lifecycle separate from the page
- Requires HTTPS in production for security reasons
- No direct DOM access — communicates with pages via postMessage