# Service workers

> Service workers intercept requests to support offline PWAs. Register a worker, manage its lifecycle, and handle scope, caching, and update problems.

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

A **service worker** is a script the browser runs in its own worker thread, separate
from any page, which can intercept network requests from the pages it controls and
answer them itself. This supports offline use and instant repeat loads. It also enables push. The worker keeps running after the tab is gone.

It has no DOM access, and it only runs in a secure context (HTTPS, or `localhost`
during development).

## The smallest one that works

Register it from the page:

```js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
} else {
  // No service worker: the site still works, it just has no offline layer.
}
```

In `/sw.js`, answer requests from a cache, falling back to the network:

```js
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((hit) => hit || fetch(event.request)),
  );
});
```

The registration and fetch handler form a working service worker. You can add
precaching and cache expiry to this implementation. You can also add an update strategy.

## The lifecycle, in one pass

A registered worker is **installed**, then **activated**, and only then does it start
controlling pages. A page loaded before the worker activated stays uncontrolled until
it is reloaded. When you ship a new `sw.js`, the browser installs it alongside the old
one and leaves it **waiting** until the old worker releases its clients, which is why
a deploy does not take effect on the very next reload unless you ask it to.

See [Service worker lifecycle](/reference/service-worker/lifecycle/) and
[The update flow and skipWaiting](/reference/service-worker/update-skipwaiting/).

## Where it commonly goes wrong

- A worker at `/js/sw.js` controls only `/js/`. Serve it from the root, or
  send `Service-Worker-Allowed`. See [Registration and scope](/reference/service-worker/registration-scope/).
- After a deploy, users keep the old version while the new worker waits behind it.
- A cache-first strategy on HTML keeps users on
  an old page. Choose a strategy for each request type; see [Caching strategies](/reference/service-worker/caching-strategies/).
- Debug the worker in its own DevTools pane; its lifecycle is separate from page code.
  See [Debugging service workers](/reference/service-worker/debugging/).

## Every topic in this section

<CardGrid>
	<LinkCard title="Service worker lifecycle" href="/reference/service-worker/lifecycle/" description="The states a service worker passes through from register() to redundant, the event at each transition, why a new version waits, and what skipWaiting() changes." />
	<LinkCard title="Service worker registration and scope" href="/reference/service-worker/registration-scope/" description="How register() binds a script to a URL-prefix scope, how the default scope and Service-Worker-Allowed bound it, how overlaps resolve, and updateViaCache." />
	<LinkCard title="Service-Worker-Allowed header" href="/reference/service-worker/service-worker-allowed/" description="How the Service-Worker-Allowed response header lets a service worker registration request a maximum path scope beyond the script's directory." />
	<LinkCard title="skipWaiting() and the update flow" href="/reference/service-worker/update-skipwaiting/" description="How the browser detects a byte-different worker script, why the new worker waits, and what skipWaiting(), clients.claim(), update(), and updateViaCache change." />
	<LinkCard title="FetchEvent and request routing" href="/reference/service-worker/fetch-event/" description="The FetchEvent members for every in-scope request, the respondWith() and waitUntil() rules and their error outcomes, and routing by destination, mode, and URL." />
	<LinkCard title="Caching strategies for service workers" href="/reference/service-worker/caching-strategies/" description="What each of the five fetch-handler strategies (Cache First, Network First, Stale-While-Revalidate, Network Only, Cache Only) returns, what it costs, the response-cloning and opaque-response traps, and the Workbox equivalents." />
	<LinkCard title="Cache API" href="/reference/service-worker/cache-api/" description="The CacheStorage and Cache interfaces behind the caches global, their members, the TypeError and QuotaExceededError conditions on add(), addAll(), and put(), and the versioned-cache pattern for install and activate." />
	<LinkCard title="Clients API" href="/reference/service-worker/clients-api/" description="The Clients interface a service worker reaches as self.clients, its get(), matchAll(), openWindow(), and claim() members, the InvalidAccessError and InvalidStateError conditions, and the notification-click focus-or-open pattern." />
	<LinkCard title="NavigationPreloadManager" href="/reference/service-worker/navigation-preload/" description="How registration.navigationPreload lets the browser fetch a navigation in parallel with service worker start-up, the enable(), disable(), setHeaderValue(), and getState() members, the InvalidStateError and TypeError conditions, and how FetchEvent.preloadResponse and the Service-Worker-Navigation-Preload header fit together." />
	<LinkCard title="Offline fallback for service workers" href="/reference/service-worker/offline-fallback/" description="How a service worker returns a precached page, image, or JSON body when a navigation or subresource request fails with nothing cached for its URL, which requests qualify, what Response.error() does, and the Workbox setCatchHandler equivalent." />
	<LinkCard title="Background Fetch API" href="/reference/service-worker/background-fetch/" description="How BackgroundFetchManager.fetch() hands a large download to the browser, which shows progress and a cancel control and wakes the service worker with backgroundfetchsuccess, backgroundfetchfail, backgroundfetchabort, or backgroundfetchclick, with the exceptions and failure reasons." />
	<LinkCard title="Periodic Background Sync API" href="/reference/service-worker/periodic-background-sync/" description="How PeriodicSyncManager.register() asks the browser to fire a periodicsync event in an installed PWA's service worker no more often than minInterval, why Chrome gates it on installation and site engagement, and the exceptions and detection pattern." />
	<LinkCard title="Workbox" href="/reference/service-worker/workbox/" description="What the Workbox 7 packages do, how precacheAndRoute() and __WB_MANIFEST build versioned caches, when GenerateSW or InjectManifest applies, and page updates." />
	<LinkCard title="Debugging service workers" href="/reference/service-worker/debugging/" description="Where Chrome DevTools, Firefox DevTools, and Safari Web Inspector expose a service worker's state, how to force an update, bypass the worker, simulate offline, inspect Cache Storage, and read worker console output, with the exact panel labels." />
	<LinkCard title="Background Sync API" href="/reference/service-worker/background-sync/" description="How SyncManager.register() defers a failed request until connectivity returns and replays it in the sync event, with exceptions, retry limits, and detection." />
	<LinkCard title="Service Worker Static Routing API" href="/reference/service-worker/static-routing/" description="How addRoutes() in the install event sends matching requests to the network, a cache, or the fetch handler before a service worker starts, and when it rejects." />
	<LinkCard title="Removing a service worker safely (kill switch)" href="/reference/service-worker/unregister-kill-switch/" description="What registration.unregister() removes, why already-controlled pages keep the old worker until they unload, and how a replacement worker clears its own caches." />
	<LinkCard title="Background sync, periodic sync, and Web Locks" href="/reference/service-worker/background-sync-vs-web-locks/" description="Choose one-off background sync, periodic background sync, or Web Locks by trigger, lifetime, support, and failure behavior." />
</CardGrid>

## Where to go next

- [Web app manifest](/reference/manifest/): the other half of an installable app.
- [Install prompt](/reference/installation/install-prompt/): what browsers require before offering installation.

← Back to the [Reference](/reference/) overview.