Skip to content
jshacks.dev
Browser

How to Register a Service Worker

Register a service worker with navigator.serviceWorker.register: scope, secure context, lifecycle, install and activate, updates, skipWaiting and debugging.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger and Postman logos.

A service worker is a script that the browser runs in the background, separate from any page, and that sits between your site and the network. It can answer requests from a cache, so a page works offline, it can receive push messages and it can run tasks when the page is closed. None of that happens until the page registers the worker, and registration has rules that trip up almost everyone the first time: it needs HTTPS, its scope depends on where the file lives, it goes through a lifecycle of install, wait and activate, and an updated worker does not take over until the old one lets go. This guide shows how to register a service worker in JavaScript: the call and the secure context requirement, the file location and scope, feature detection, the lifecycle events, how updates are detected and applied, skipWaiting() and clients.claim() and their trade-offs, unregistering, debugging in the developer tools and common failures. The API is documented on MDN and is supported by all current browsers.

Register from the page

Registration is one call on navigator.serviceWorker, made from the page, that returns a promise for a ServiceWorkerRegistration. Check that the API exists first, and register after the page has loaded, so that the work of installing the worker does not compete with the resources the page needs.

register.jsJavaScript
if ("serviceWorker" in navigator) {
  window.addEventListener("load", async () => {
    try {
      const registration = await navigator.serviceWorker.register("/sw.js");
      console.log("registered with scope", registration.scope);
    } catch (error) {
      console.error("service worker registration failed:", error);
    }
  });
}
Text
registered with scope https://example.com/

Registering the same script again is harmless, since the browser checks whether it changed, so this code can run on every page view. The promise resolves when registration succeeds, which is before the worker is installed or active, and rejects if the script cannot be fetched, has a syntax error or is blocked by the rules below.

Secure context only

Service workers can intercept all requests, so browsers allow them only on secure origins: https:// pages and http://localhost for development. Registering on an ordinary HTTP page fails, and navigator.serviceWorker is undefined. Serve your production site over HTTPS, and use localhost for local work. The worker script itself must be served with a JavaScript MIME type, and from the same origin as the page, so you cannot register a worker hosted on a CDN domain.

Scope: what the worker controls

The scope is the set of URLs a worker can control, and by default it is the directory containing the script. A worker at /sw.js controls everything under /, while one at /app/sw.js controls only paths that start with /app/. This is why the worker file is usually placed at the site root, even when the rest of the scripts live in a folder.

scope.jsJavaScript
// /app/sw.js controls /app/ and below
const a = await navigator.serviceWorker.register("/app/sw.js");
console.log(a.scope);

// Request a narrower scope with an option
const b = await navigator.serviceWorker.register("/sw.js", { scope: "/shop/" });
console.log(b.scope);
Text
https://example.com/app/
https://example.com/shop/

A scope can be narrower than the default, never wider, unless the server sends a Service-Worker-Allowed header on the script with a path that permits it. Also, each scope has at most one active registration, so registering a different script for the same scope replaces the first. If pages mysteriously stop being controlled, an accidental scope mismatch is a common reason.

The lifecycle

A worker moves through states, and each transition fires an event inside the worker. After registration, the browser downloads the script and starts the install step. The install event runs once for each new version, and is the place to cache the files your app needs offline. When installation finishes, the worker waits if an older version still controls open pages, and otherwise moves on to activation. The activate event runs when the worker takes over, and is where you remove outdated caches. After that, the worker handles fetch events for pages in its scope.

sw.jsJavaScript
const CACHE = "app-v1";
const ASSETS = ["/", "/styles.css", "/app.js", "/offline.html"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(ASSETS)));
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(names.filter((name) => name !== CACHE).map((name) => caches.delete(name))),
    ),
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => cached ?? fetch(event.request)),
  );
});
Text
(files are cached on install, old caches are removed on activate and requests are answered from the cache first)

event.waitUntil() tells the browser to keep the worker alive until a promise settles, because a worker can be stopped at any time when idle. If a promise passed to waitUntil() in install rejects, for example because one of the cached files is missing, the whole installation fails and the old worker stays in place, so keep the list of precached files accurate. The caching strategy in fetch is deliberately simple here; the guide on caching assets for offline use covers the common strategies.

First load is not controlled

A page that was loaded before the worker existed is not controlled by it, even after the worker activates. The worker takes over pages only on the next navigation, or when it calls clients.claim() during activation. Many people see this and conclude that registration failed. Check navigator.serviceWorker.controller, which is null on an uncontrolled page.

controller.jsJavaScript
console.log(navigator.serviceWorker.controller ? "controlled" : "not controlled yet");

navigator.serviceWorker.addEventListener("controllerchange", () => {
  console.log("a new worker is now in control");
});
Text
not controlled yet

Calling self.clients.claim() in the activate handler makes the worker control existing pages at once. That is convenient for the first visit, but it can surprise a page that was loaded by an older worker with a new worker's cache layout, so use it with care.

Updates

On each navigation within the scope, and at least every 24 hours, the browser fetches the worker script again and compares it byte by byte with the installed version. Any difference, even a comment, counts as a new version. The new worker installs in the background, and then waits until no page is controlled by the old worker, which means until every tab of the site is closed, or navigated away. This protects pages from having their cached files change under them, but it means a visitor who never closes the tab keeps the old version.

updates.jsJavaScript
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) {
      console.log("a new version is ready");
      showUpdateBanner(registration);
    }
  });
});
Text
a new version is ready

The updatefound event fires when a new worker starts installing, and its installed state with an existing controller means that an update is waiting. A friendly pattern is a banner that says "A new version is available. Reload", which tells the waiting worker to take over and reloads the page.

banner.jsJavaScript
function showUpdateBanner(registration) {
  const button = document.querySelector("#update");
  button.hidden = false;
  button.addEventListener(
    "click",
    () => registration.waiting?.postMessage({ type: "SKIP_WAITING" }),
    { once: true },
  );
}

navigator.serviceWorker.addEventListener("controllerchange", () => {
  window.location.reload();
});
message.jsJavaScript
// in sw.js
self.addEventListener("message", (event) => {
  if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});
Text
(clicking the banner activates the new worker and reloads the page)

self.skipWaiting() makes a waiting worker activate immediately instead of waiting for tabs to close. Calling it automatically in install gives instant updates, but it can break a page that is open and still using the old assets, so the user-triggered version above is the safer route.

Force a check for updates

A long-running page can ask the browser to look for a new worker with registration.update(), for instance on an interval or when the tab becomes visible.

check.jsJavaScript
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") registration.update();
});
Text
(the browser fetches sw.js again when the user returns to the tab)

Make sure the server does not cache sw.js for long. The browser bypasses the HTTP cache for the worker script by default in modern versions when checking updates, but a CDN in front of the site might not, so serve it with Cache-Control: no-cache.

Unregister

During development or in a rollback, you may need to remove a worker. registration.unregister() removes it, and the page keeps being controlled until it is closed or reloaded.

unregister.jsJavaScript
const registrations = await navigator.serviceWorker.getRegistrations();
for (const registration of registrations) {
  await registration.unregister();
}
console.log("removed", registrations.length);
Text
removed 1

Unregistering does not delete the caches that the worker created, so remove them with caches.keys() and caches.delete() as well if you want a clean state. If a faulty worker is stuck, shipping a replacement script that unregisters itself and clears caches is the way to recover users you cannot reach.

Debugging

The Application panel in Chromium-based developer tools, and the equivalent panel in Firefox, shows the registered workers, their state and scope, and offers buttons to unregister, update and skip waiting. The option "Update on reload" makes the browser fetch the script on each reload, which removes the waiting step while developing, and "Bypass for network" ignores the worker for requests. The cache storage view lists what is stored. Console messages from the worker appear in the same console, labeled by source. When something does not work, check that the page is on HTTPS or localhost, that the script path is correct and returns a 200 with a JavaScript type, that the scope covers the page and that no syntax error stops the script.

Common failures

A 404 on the script path, usually from using a relative path that resolves differently on nested pages, so write the path from the root. A redirect on the script URL, which is not allowed. A worker file with a MIME type of text/html, which happens when a catch-all route returns the app shell for unknown paths. Registering from inside an iframe on another origin. Caching the worker script with a long lifetime, so updates never arrive. Precaching a file that returns an error, which fails installation silently on the user's device. And cache versions that are never cleaned, filling the user's storage.

Security and privacy

A worker can see and alter every request in its scope, so protect the script like the rest of your code, and never pull the worker from a source you do not control. Do not cache responses that contain private data in a shared cache, and clear caches on sign-out. Because workers are persistent, a bug in one can affect users until the next update, so test changes carefully, and keep the ability to ship a corrected worker quickly.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.