Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Service Workers: Caching Strategies, Offline Applications and Lifecycle

A service worker runs outside the document context and can handle requests made by a controlled web application. Registering one does not make an application offline-ready. We will build a deliberately narrow fallback for a public documentation site, then choose caching policies for other resource types.

Published Written by Reading time 13 min read
On this page Contents: quick navigation between sections

Architecture and scope

A service worker has its own execution context without DOM access. The browser may stop it and start it again for another event, so globals are not durable storage. Registration requires a secure context, normally HTTPS, with localhost a common development exception. The script must be same-origin; its directory determines the default scope, and the Service-Worker-Allowed header can widen the permitted scope. [1][2][17]

Scope identifies controlled documents, not a list of cacheable resource URLs. A controlled document can also initiate cross-origin requests. Our example explicitly restricts handling to the same origin and selected paths. [1][17]

Registration and lifecycle

register.ts

export async function registerOfflineWorker(): Promise<void> {
  if (!("serviceWorker" in navigator)) {
    return;
  }

  try {
    await navigator.serviceWorker.register("/service-worker.js", {
      scope: "/",
      type: "module",
    });
  } catch (error: unknown) {
    console.error("Service worker registration failed:", error);
  }
}

void registerOfflineWorker();

index.html

<script type="module" src="/register.js"></script>

Register a stable /service-worker.js URL. The install event prepares resources via event.waitUntil(); a rejected promise makes installation fail. A new version normally waits until its predecessor no longer controls clients. During activate, clean up storage owned by this module. [2][3]

First registration does not mean the current document is controlled; the next navigation is usually needed. register() confirms registration, not offline readiness. Compile register.ts against DOM and service-worker.ts against WebWorker; load the registration output as an external type="module" script. Deploy the worker module at the site root. [2][17]

Cache Storage versus HTTP cache

Related guide: Caching in web applications: browser, CDN and Redis.

Cache Storage keeps Request/Response pairs in named caches. HTTP Cache-Control and expiry dates do not automatically govern those entries; matching considers URL, method and Vary, among other factors. Do not ignore query parameters or Vary without a defined reason. A worker's fetch can still use the HTTP cache, so Network First does not necessarily contact the origin server. [4][5]

Use cache.addAll() for a known set of public files, not arbitrary URLs. cache.put() is not restricted to successful responses; check status, type, redirects and data policy before runtime writes. A response body is a stream consumed once, so clone it before returning and storing it in parallel. Do not cache partial 206 responses. [4][12]

Five strategies and their trade-offs

Cache First returns a stored response, otherwise tries the network; use it for public content-hashed assets. Network First tries the network before using a stored response on a defined failure; useful for freshness-sensitive public content. Stale While Revalidate serves a saved response immediately and refreshes it in the background; the user may see an earlier version. [5][6]

Network Only neither reads nor writes Cache Storage; prefer it for account operations and payments, with separate HTTP-cache controls. Cache Only depends on pre-existing entries. Decide explicitly whether 5xx or timeouts count as failures: fetch rejects on network errors, not on every HTTP error. Use waitUntil() to extend the event for background writes. [3][6][16]

Complete example: public offline fallback

service-worker.ts

/// <reference lib="webworker" />

declare const self: ServiceWorkerGlobalScope;

const worker = self;
const CACHE_PREFIX = "polprog-offline-demo-";
const CACHE_NAME = `${CACHE_PREFIX}v1`;
const OFFLINE_PAGE = "/offline.html";
const PUBLIC_ASSETS = [OFFLINE_PAGE, "/offline.css"];
const PUBLIC_PAGES = new Set(["/", "/docs"]);

async function install(): Promise<void> {
  const cache = await caches.open(CACHE_NAME);
  const requests = PUBLIC_ASSETS.map(
    (path) =>
      new Request(new URL(path, worker.location.origin), {
        cache: "reload",
        credentials: "omit",
        redirect: "error",
      }),
  );

  await cache.addAll(requests);
}

async function activate(): Promise<void> {
  const names = await caches.keys();
  const obsolete = names.filter(
    (name) => name.startsWith(CACHE_PREFIX) && name !== CACHE_NAME,
  );

  await Promise.all(obsolete.map((name) => caches.delete(name)));
}

async function cachedResponse(
  request: RequestInfo,
): Promise<Response | undefined> {
  try {
    const cache = await caches.open(CACHE_NAME);

    return await cache.match(request);
  } catch {
    return undefined;
  }
}

async function navigate(request: Request): Promise<Response> {
  try {
    return await fetch(request);
  } catch {
    const offline = await cachedResponse(OFFLINE_PAGE);

    if (offline) {
      return offline;
    }

    return new Response("Offline. Please reconnect and retry.", {
      status: 503,
      headers: { "Content-Type": "text/plain; charset=utf-8" },
    });
  }
}

async function staticAsset(request: Request): Promise<Response> {
  const cached = await cachedResponse(request);

  return cached ?? fetch(request);
}

worker.addEventListener("install", (event) => {
  event.waitUntil(install());
});

worker.addEventListener("activate", (event) => {
  event.waitUntil(activate());
});

worker.addEventListener("fetch", (event) => {
  const { request } = event;
  const url = new URL(request.url);

  if (
    request.method !== "GET" ||
    url.origin !== worker.location.origin ||
    url.search ||
    request.headers.has("Range") ||
    request.headers.has("Authorization")
  ) {
    return;
  }

  if (request.mode === "navigate" && PUBLIC_PAGES.has(url.pathname)) {
    event.respondWith(navigate(request));
    return;
  }

  if (PUBLIC_ASSETS.includes(url.pathname)) {
    event.respondWith(staticAsset(request));
  }
});

export {};

This worker precaches only two fixed public files: /offline.html and /offline.css. The server must serve them independently of session state, without redirects and with correct MIME types. Install requests omit credentials and reload the HTTP cache; a failed fetch rejects installation. Increment the cache version with each release that changes the offline files. [1][3][4]

Navigations to / and /docs try the network and serve the offline document if fetch rejects; 404 and 500 responses pass through. Dynamic HTML and API responses are never saved. The two static resources are Cache First with no runtime writes. Other paths, query strings, Range, Authorization and non-GET methods pass through. This is intentionally a small fallback, not a fully offline application. [1][6][16]

Offline document and accessibility

offline.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Offline</title>
    <link rel="stylesheet" href="/en/offline.css" />
  </head>
  <body>
    <main>
      <h1>You are offline</h1>
      <p>Reconnect to the internet, then reload this page.</p>
      <p><a href="/en">Return to the home page</a></p>
    </main>
  </body>
</html>

offline.css

:root {
  color-scheme: light dark;
  font-family: system-ui, sans-serif;
}

body {
  margin: 0;
  padding: 2rem;
}

main {
  max-width: 40rem;
  margin-inline: auto;
}

A standalone page has a clear heading, explains the lack of connection and offers a link home. Its separate stylesheet needs no external resources. Publish the files before registering the worker. The UI example is in English; localize the production UI and its lang attribute. [1]

If storage is cleared, the worker may still be active but unable to retrieve the offline document; it returns a plain-text 503 instead. A stored fallback may carry status 200, which does not establish that the original route succeeded. Never replace a failed JSON request with an HTML document. [1][4]

Updating without version conflicts

We deliberately avoid unconditional skipWaiting() and clients.claim(). Taking over a document early can combine old page code with a new asset set. The normal waiting phase reduces the risk but does not replace compatible deployment. Retain previous versioned assets on the server for a transition period. [2][7]

Publish assets before the worker script, keep the script URL stable and use HTTP policies that allow update checks. For a user-driven update, detect a waiting worker, preserve unsaved state, coordinate reloading every tab and only then activate. Remove caches only by your own unique prefix, never every cache in the origin. [7]

Optional Navigation Preload can start a navigation request while the worker boots. In activate, detect registration.navigationPreload, enable it, and consume event.preloadResponse when handling navigation. If absent, use ordinary fetch; also handle rejection of the preload promise. [8]

The small example leaves this feature disabled because it handles only selected navigations. When extending it, account for every navigation in scope and avoid fetching an already available response twice. If the server varies content based on Service-Worker-Navigation-Preload, return the corresponding Vary header. [8][13]

Security, freshness and storage limits

Do not automatically store /api responses, account pages, financial data, tokens or cookie-dependent responses. A 200 status is not proof of public content. Cache Storage does not automatically partition entries by signed-in user. On logout or account changes, remove deliberately designed private local data if the application stores any at all. [4][14]

For public runtime caching, use a route allowlist, maximum age, entry limits and write-failure handling. Quotas vary by browser; storage may reject writes or be evicted under pressure. navigator.storage.estimate() gives an approximate usage picture. Do not make a successful online request depend on saving a copy. [9][11]

Background Sync and mutations

Background Sync can retry work when connectivity returns, but it is not universally supported and does not guarantee execution at a particular time. A durable IndexedDB queue should store minimal data, status and an operation identifier; also provide a manual retry path. [10][15]

A POST may be processed by the server before its response is lost, so retries can duplicate side effects. Use an idempotency key enforced by the backend, recheck authorization on replay and cap retries. Do not confirm a write to the user before the server acknowledges it; display a pending state. Do not store tokens in the queue. [10][15]

Workbox or a custom worker?

For a larger asset catalog, Workbox can generate a revisioned precache manifest and match strategies to routes. ExpirationPlugin limits entry count and age; combine it with an explicit response-admission policy. Expiration is not a guarantee of instantly rejecting every stale response, so critical data needs its own freshness policy. [6][11]

A custom worker makes sense for small, tightly bounded requirements. Workbox removes boilerplate but does not automatically solve authorization, version conflicts or privacy. Do not run competing workers for the same scope; choose one implementation and test the generated output. [6][7]

Testing and release criteria

Test a first visit without a worker, a return visit after activation, network loss, 404 and 500, installation failure for one resource and cleared storage. Deploy v2 with two tabs open and observe waiting; check that assets required by the old page remain available. [1][2]

Verify that POST, account paths, cross-origin requests, query strings and Range do not enter storage. Test account switching, quota errors, real network interruption and recovery. DevTools can inspect workers and Cache Storage, but integration tests in target browsers remain necessary. Do not claim full offline support when only a fallback page has been tested. [9][14]

Start with a small set of public files and clearly define which tasks work without connectivity. Expand caching only where its benefit justifies the cost of managing freshness, security and versions.

JavaScript TypeScript Service Workers Cache Storage PWA Offline Workbox Web Performance

Frequently asked questions

Does a service worker control the first visit?

Not necessarily. A newly registered worker usually controls the document on a subsequent navigation. Inspect navigator.serviceWorker.controller. [1][2]

Are a PWA and a service worker the same thing?

No. A service worker is a web platform mechanism; a PWA is a broader approach to delivering an application experience. [1]

Does Cache-Control: no-store prevent cache.put()?

No. Cache Storage does not enforce HTTP caching headers automatically. Code must exclude private and no-store responses. [4][14]

Does fetch reject on HTTP 404?

No. The HTTP response is available; inspect status or ok. The example preserves 404 rather than treating it as a network outage. [1]

Is it safe to call skipWaiting() on every release?

No. Replacing the worker in open tabs can break asset compatibility. Coordinate updates. [7]

Does the cache disappear when the tab closes?

Not necessarily. It belongs to browser storage, but users or the browser may remove it. [4][9]

Can POST be stored in Cache Storage?

Cache.put() requires GET. Use a separately designed queue and server-side idempotency for retrying mutations. [12][10]

Does Background Sync guarantee an order will be sent?

No. Availability and timing depend on the browser. Maintain a pending state, manual retry and server-side deduplication. [10][15]

Can a service worker use localStorage?

No. It is a synchronous Window API. Use a storage mechanism such as IndexedDB for durable structured data. [1]

Should offline.html replace all API failures?

No. Returning HTML instead of JSON violates the API contract. Restrict the fallback to appropriate navigations. [1]

Sources and references

  1. MDN, Using Service Workers↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12↩13
  2. web.dev, Service workers↩1↩2↩3↩4↩5↩6↩7
  3. MDN, ExtendableEvent.waitUntil()↩1↩2↩3
  4. MDN, Cache↩1↩2↩3↩4↩5↩6↩7↩8
  5. web.dev, Service worker caching and HTTP caching↩1↩2
  6. Chrome for Developers, Workbox caching strategies↩1↩2↩3↩4↩5
  7. web.dev, Update↩1↩2↩3↩4↩5
  8. MDN, NavigationPreloadManager↩1↩2
  9. MDN, Storage quotas and eviction criteria↩1↩2↩3
  10. MDN, Background Synchronization API↩1↩2↩3↩4↩5
  11. Chrome for Developers, workbox-expiration↩1↩2
  12. MDN, Cache.put()↩1↩2
  13. MDN, Service-Worker-Navigation-Preload header↩
  14. MDN, Cache-Control↩1↩2↩3↩4
  15. Chrome for Developers, workbox-background-sync↩1↩2↩3↩4
  16. MDN, Using the Fetch API↩1↩2
  17. MDN, ServiceWorkerContainer.register()↩1↩2↩3

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning