Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Dev

Offline-First PWA Caching: Service Workers and Safe Updates

By: Md Tarek · 17 Oct 2026

Offline-first PWA caching with a service worker and local app data
Offline-first PWA caching with a service worker and local app data

An offline-first PWA should make a deliberate promise: the app shell and previously saved user content remain useful when connectivity disappears, while operations that require current server state stay honest about their limits. The reliable way to make that promise is to combine a service worker with narrowly scoped caches, a network policy chosen per request, and an update flow that never silently mixes incompatible versions.

What the service worker actually controls

A service worker is an event-driven worker that can sit between a page, the browser, and the network. It can intercept requests and return a response from Cache Storage, the network, or a fallback. It has no DOM access and runs asynchronously, so UI state and worker state must communicate through messages rather than shared variables. Service workers require a secure context: production means HTTPS, while localhost is treated as secure for development. [1]

The lifecycle matters. A new worker is downloaded, installed, and then activated. During an update, the new worker normally installs in the background and waits while pages are still controlled by the old worker. The install event is a good place to precache the minimum shell; activate is the point to remove obsolete caches. event.waitUntil() keeps those asynchronous operations attached to the lifecycle instead of allowing them to be cut short. [1] [2]

That minimum shell should be small: the document needed to boot, hashed JavaScript and CSS, icons, and a useful offline page. Do not treat precaching as a license to copy an entire site. Every byte competes for device storage, and cached content can become stale or expose data longer than intended.

Choose a strategy for each request

Cache Storage is separate from the browser’s ordinary HTTP cache, and a service worker does nothing with it unless its fetch handler explicitly applies a policy. [3] That separation is useful, but it also creates two layers whose expiry rules can conflict.

For versioned static assets, cache-first is usually predictable: return the cached file, then let a new release introduce new filenames or a new cache namespace. For navigations, network-first keeps online HTML current and falls back to an offline document when the request fails. For a feed where an immediate response matters more than perfect freshness, stale-while-revalidate can return the cached response and refresh it for a later visit. Payments, account balances, checkout, and other correctness-sensitive operations should be network-only; an old response is not an acceptable substitute for current server state. These are documented tradeoffs, not a universal recipe. [3]

Here is a compact worker illustrating versioned precaching, network-first navigations, cache-first static files, and conservative cleanup:

const CACHE = "app-v3";
const SHELL = ["/", "/index.html", "/styles.css", "/app.js", "/offline.html"];

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

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys
          .filter((key) => key.startsWith("app-") && key !== CACHE)
          .map((key) => caches.delete(key))
      )
    )
  );
});

self.addEventListener("message", (event) => {
  if (event.data?.type === "ACTIVATE_UPDATE") self.skipWaiting();
});

self.addEventListener("fetch", (event) => {
  const { request } = event;
  if (request.method !== "GET") return;

  if (request.mode === "navigate") {
    event.respondWith(
      fetch(request).catch(async () => {
        const offline = await caches.match("/offline.html");
        return offline ?? new Response("You are offline.", {
          status: 503,
          headers: { "Content-Type": "text/plain; charset=utf-8" }
        });
      })
    );
    return;
  }

  const url = new URL(request.url);
  const isStatic =
    url.origin === self.location.origin &&
    /\.(?:js|css|png|svg|woff2)$/.test(url.pathname);

  if (isStatic) {
    event.respondWith(
      (async () => {
        const cached = await caches.match(request);
        if (cached) return cached;
        const response = await fetch(request);
        if (response.ok) {
          const cache = await caches.open(CACHE);
          await cache.put(request, response.clone());
        }
        return response;
      })()
    );
  }
});

In a real build, generate SHELL from the build manifest so filenames cannot drift away from the worker. Cache only same-origin, deliberately selected responses. Do not put authenticated API responses or secrets in a broad static cache; use an explicit data policy and consider whether the response should persist at all. If offline writes matter, keep pending records in a durable client-side store, make retries idempotent, and design server-side conflict handling. A cached GET does not make a POST safe to replay.

Ship updates without breaking open tabs

The safest default is an atomic release. Publish the new worker and all assets it references, install them into a new cache name, and delete old caches only in activate. The previous worker and its cache remain available if installation fails, while the new worker is waiting. MDN’s update example follows this versioned-cache pattern. [2]

On the page, detect registration.waiting or an updatefound event and show a modest “Update available” action. Only after the user accepts should the page send { type: "ACTIVATE_UPDATE" } to the waiting worker. Then reload after the new controller is ready. Avoid calling skipWaiting() unconditionally: forcing activation can leave an open page running old JavaScript against a worker that expects new routes or data shapes. Clients.claim() also changes takeover timing, so use it only when the application has been tested for mixed-version behavior. The platform models installing, waiting, and active workers separately for precisely this transition. [4]

Keep the worker script itself easy to fetch and test, and use content-hashed asset names or a build-generated manifest. Remember that HTTP caching still participates in the path to a response; service-worker and HTTP-cache policies can have different lifetimes, so cache-busting and response headers must agree with the release plan. [3] Test first install, upgrade with two open tabs, offline navigation, a failed precache, cleared storage, private browsing, and a server response that changes shape.

Common mistakes

The most damaging mistake is caching every request with one cache-first rule. It produces an app that appears reliable while showing stale permissions, records, or prices. Another is deleting the old cache during install, which can strand the currently active worker. A third is precaching an HTML shell that references assets absent from the same release. Finally, an “offline” badge that merely checks navigator.onLine is not proof that the server is reachable; treat actual request failures as the signal and explain which actions are unavailable.

FAQs

Does an offline-first PWA work without a service worker?

Not with service-worker-controlled request routing. The browser’s HTTP cache can still help, but it does not provide the same programmable offline fallbacks or request-specific policies. [1] [3]

Should every update activate immediately?

No. Immediate activation is appropriate only when old pages remain compatible with the new worker. For most apps, install in the background, tell the user an update is ready, activate on consent, and reload into one coherent release.

References

[1] Service Worker API - MDN Web Docs

[2] Using Service Workers - MDN Web Docs

[3] Service worker caching and HTTP caching - web.dev

[4] Service Workers - W3C Recommendation