Service Workers — Offline Architecture for Modern Web Apps
Your web app has a second home. A programmable proxy that lives between your page and the network — intercepting requests, caching responses, and waking up to deliver push notifications even when the browser is closed. Service workers are what turn a website into a resilient, app-like experience. This guide covers the lifecycle, every caching strategy worth knowing, offline architectures with IndexedDB, background sync, push notifications, and production Workbox patterns.
FrontendX Engineering · System Design Series
What Makes Service Workers Different?
A service worker is a JavaScript file that runs in the background — independent of your web page. Think of it as a programmable proxy sitting between your app and the network. It can intercept every HTTP request your page makes, serve cached responses when the network is slow or unavailable, and even wake up to handle push events while the browser is closed.
But service workers are not like normal JavaScript. They have no access to the DOM, they require HTTPS (except on localhost), they follow a strict lifecycle managed entirely by the browser, and they can be killed at any moment when idle. Understanding these constraints is the first step to building with them.
Here is what makes service workers fundamentally different from your page's JavaScript:
No DOM Access
Service workers run in a worker context — no window, no document. They cannot directly manipulate the page. Communication happens via postMessage.
HTTPS Only
Service workers require a secure origin. This protects users from man-in-the-middle attacks that could inject malicious service workers.
Event-Driven Lifecycle
Install → Activate → Fetch. The browser controls the lifecycle completely. Your code reacts to events.
Killable by Browser
The browser can terminate a service worker at any time when it is idle. Do not rely on long-lived state in global variables.
Scoped by Path
A service worker only controls pages under its registration scope. Register at / to control the whole origin.
Update Flow
The browser checks for updates on every navigation. Byte-different scripts trigger a new install → waiting → activate cycle.
1 · Service Worker Lifecycle
The service worker lifecycle is the hardest part to get right, because it is event-driven and runs asynchronously alongside your page. Understanding it is table stakes for production service worker development.
Registration
Everything starts with a call to navigator.serviceWorker.register() from your page's JavaScript. This tells the browser to download the service worker script, parse it, and begin the installation phase.
Always check "serviceWorker" in navigator before calling register. Some browsers (or private browsing modes) do not support service workers, and the call will throw.
Install Event
The install event fires when the browser has successfully downloaded and parsed the service worker script. This is your first chance to do work — and it is almost always used for pre-caching your app's critical assets.
event.waitUntil() is the key API here. It keeps the service worker in the installing state until the promise resolves. If the promise rejects — say, one of thecache.addAll() URLs returns a 404 — the installation fails entirely and the browser discards this worker. This is by design: you either get everything you need, or you fail fast.
Key Insight
The install event is all-or-nothing. If any pre-cached resource fails to download, the entire service worker installation fails. This guarantees that your app shell is always fully available when the service worker is active.
Activate Event
Once installed, the service worker moves to the "waiting" state if an older version is already controlling pages. It only activates when all controlled pages are closed — unless you callself.skipWaiting().
The activate event is where you clean up after your old self: delete stale caches, migrate data structures, and claim uncontrolled clients with self.clients.claim().
Do not skip the activate event's cache cleanup. If you never delete old caches, your user's browser accumulates every version of your cached assets forever — potentially gigabytes of stale data that the browser's storage quota will eventually start evicting.
Fetch Event
After activation, every HTTP request from controlled pages passes through the service worker's fetch event listener. This is where you decide: serve from cache, fetch from network, or some combination of both.
The critical rule: you must call event.respondWith(). If you do not, the browser falls through to its default network behavior — which defeats the entire purpose of having a service worker.
Service worker lifecycle — registration through activation, with skip waiting shortcut and termination on idle
The Update Flow
When the page calls register() again (on every navigation), the browser downloads the script and compares it byte-for-byte. If anything changed, the new worker goes through the full lifecycle: install → waiting → activate. The old worker keeps controlling open pages until all are closed.
Use self.skipWaiting() + self.clients.claim() in development, but consider letting users finish their session before updating in production. Notifying the user "A new version is available" gives them control over when to refresh.
2 · Caching Strategies
The choice of caching strategy is the single biggest architectural decision you will make with service workers. Each strategy trades off freshness against speed against resilience. There is no best strategy — only the right one for the resource you are serving.
Caching strategy decision flow and comparison — each strategy trades off freshness vs speed vs resilience
Cache First (Cache with Network Fallback)
This is the ideal strategy for versioned, immutable assets — CSS files with content hashes, JavaScript bundles, web fonts. The service worker checks the cache first. If found, it returns immediately — zero network latency. If not found, it fetches from the network, caches the response, and returns it.
Cache First works because versioned assets are immutable. When the content changes, the filename changes too ( main.abcd1234.js ). The old cache entry is never hit again, and the new asset is cached on first request.
Network First (Network with Cache Fallback)
For API responses and HTML pages, freshness matters more than speed. Network First tries the network first, caches the response, and only falls back to the cache when the network request fails — either because the user is offline or the server is unreachable.
network-first.jsjavascript
// Network First — for API calls and pagesself.addEventListener("fetch", (event) => { if (event.request.url.includes("/api/")) { event.respondWith( fetch(event.request) .then((response) => { const clone = response.clone(); caches.open("api-cache") .then((cache) => cache.put(event.request, clone)); return response; }) .catch(() => caches.match(event.request)), ); }});
The tradeoff is obvious: every request waits for the network, making this slower than Cache First when online. But it ensures the user always sees fresh data — and still has something to look at when offline.
Stale-While-Revalidate
This is the pragmatic middle ground. Serve the cached version immediately (even if it is stale), then fetch the latest from the network in the background and update the cache. Next time, the fresh version is served.
Stale-While-Revalidate is the ideal strategy for profile avatars, news feed items, and any content that changes frequently but does not require perfect freshness.
Cache Only & Network Only
Cache Only never hits the network — it only responds from cache. Use it for offline-only pages or fully pre-cached apps where every resource is installed upfront.
Network Only never uses the cache — it always goes to the network. Use it for payment forms, real-time data, or any operation where staleness is unacceptable.
Strategy Routing by URL
In production, you rarely apply a single strategy to all requests. Instead, you route each request to the right strategy based on its URL pattern and the request's destination:
strategy-router.jsjavascript
// Route requests to different strategies by URLself.addEventListener("fetch", (event) => { const { request } = event; const url = new URL(request.url); // Google Fonts — Cache First if (url.origin === "https://fonts.googleapis.com") { event.respondWith(cacheFirst(request)); return; } // API calls — Network First if (url.pathname.startsWith("/api/")) { event.respondWith(networkFirst(request)); return; } // Images — Stale-While-Revalidate if (request.destination === "image") { event.respondWith(staleWhileRevalidate(request)); return; } // Navigation — Network First with offline fallback if (request.mode === "navigate") { event.respondWith(networkFirstWithFallback(request)); return; }});
3 · Pre-caching
Pre-caching is the practice of populating the cache during the install event so that resources are available immediately — even before the user requests them. This is how your app shell loads instantly on repeat visits.
The install event we saw earlier is a pre-cache pattern. By adding cache.addAll(["/", "/offline.html"]), you guarantee that your app's entry point and offline fallback are always available from the moment the service worker is active.
Pre-caching requires careful version management. Every time any pre-cached file changes, you must increment your cache name (e.g.,precache-v2), install the new worker, and delete the old cache during activation. This is why automated tools like Workbox generate cache manifests automatically — they compute content hashes and handle the versioning for you.
Key Insight
Pre-cache your app shell, offline page, and critical CSS/JS. Let everything else be cached at runtime. Over-pre-caching delays installation and wastes bandwidth on resources the user may never visit.
4 · Runtime Caching
Unlike pre-caching (which happens at install time), runtime caching happens on-demand when the service worker intercepts a fetch event. This is where you implement the strategies from the previous section in response to real user requests.
Runtime caching is opportunistic: the first time a user visits a page or fetches an API endpoint, the response is cached. On subsequent visits, the cached response is served according to your strategy. Over time, the cache fills with exactly the resources your users actually need.
A common production pattern is combining pre-caching for the app shell with runtime caching for API responses, images, and third-party resources:
Set cache size limits for runtime caches. Without limits, an aggressively-cached image gallery can consume hundreds of megabytes. Workbox's ExpirationPlugin gives you max entries and max age controls.
5 · Offline Fallback
Every offline-first app needs a fallback page when the user navigates to a URL that is not cached. Without this, the user sees the browser's built-in error page — which immediately breaks the app-like experience you worked so hard to build.
Make sure /offline.html is pre-cached during install. It should be minimal — just enough to tell the user they are offline and offer a "Retry" button or a link back to the home page.
The page also needs to know when it is offline so it can adjust the UI. Listen for the online and offline events on window:
Do not forget the offline fallback. It is the single most common omission in real-world service worker implementations. Without it, a user who navigates while offline lands on Chrome's "dinosaur game" page — and they will not come back.
6 · IndexedDB + Service Worker Sync
The Cache API is excellent for storing HTTP responses, but it has limitations. It is not designed for structured data, complex queries, or mutations. That is where IndexedDB comes in.
Service workers can read and write to IndexedDB directly. This enables a powerful architecture for offline data access: the service worker reads from IndexedDB when network requests fail, the page writes changes to IndexedDB optimistically, and the service worker syncs queued changes when connectivity returns.
Here is how a service worker reads from IndexedDB as a cache fallback:
sw-indexeddb.jsjavascript
// Reading from IndexedDB as cache fallbackself.addEventListener("fetch", (event) => { if (event.request.url.includes("/api/posts")) { event.respondWith( fetch(event.request) .then((response) => { response.clone().json().then((data) => { saveToIndexedDB("posts", data); }); return response; }) .catch(async () => { const data = await readFromIndexedDB("posts"); return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" }, }); }), ); }});
Key Insight
IndexedDB in the service worker is the foundation of offline-first architectures. The Cache API holds HTTP responses; IndexedDB holds application data. They work together — the cache stores what the network returns, and IndexedDB stores what the user creates offline.
The Sync Queue Pattern
For mutations, use a queue stored in IndexedDB. When the user creates, updates, or deletes data while offline, the mutation is queued locally. When connectivity returns, the queue is drained:
sync-queue.jsjavascript
async function createPost(post) {
// Optimistically update the UI
addPostToUI(post);
// Queue the mutation in IndexedDB
await addToSyncQueue({
url: "/api/posts",
method: "POST",
body: post,
timestamp: Date.now(),
});
// Try to send immediately
try {
await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(post),
});
await removeFromSyncQueue(post.id);
} catch {
// Stay in queue — Background Sync will retry later
}
}
7 · Background Sync
Background Sync is a service worker API that lets you defer actions until the user has stable connectivity. Unlike a simple fetch-with-retry, the browser guarantees that the sync event will fire — even if the user closes the tab.
The browser decides when to fire the sync event. It typically fires immediately if the device is online, as soon as connectivity returns if it was offline, and with exponential backoff on failure.
background-sync.jsjavascript
// In the page — register a syncnavigator.serviceWorker.ready.then((reg) => { return reg.sync.register("sync-posts");});// In the service worker — handle the syncself.addEventListener("sync", (event) => { if (event.tag === "sync-posts") { event.waitUntil(syncPosts()); }});async function syncPosts() { const queue = await getSyncQueue(); for (const item of queue) { try { await fetch(item.url, { method: item.method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(item.body), }); await removeFromSyncQueue(item.id); } catch { break; // Will retry on next sync event } }}
Note
Background Sync requires the service worker to be installed and active. The sync tag identifies the specific sync operation — you can register multiple sync events with different tags and handle them independently.
Key Insight
Background Sync is what makes offline mutations reliable. The user writes a comment on a plane, closes their laptop, and three hours later when they connect to Wi-Fi at the hotel, the comment posts automatically. No manual retry, no lost data.
8 · Push Notifications
Push notifications combine two APIs: the Push API (server sends a message to the service worker) and the Notification API (the service worker shows a notification to the user).
The server never sends data directly to the browser. Instead, it sends a push message to the browser's push service, which forwards it to the correct device — even if the browser is closed. The service worker wakes up, processes the event, and shows a notification.
Push notifications require the user's explicit permission. CallNotification.requestPermission() in response to a user gesture (button click), never on page load.
Subscription Flow
To receive push notifications, the page must subscribe to the push service through the service worker:
The userVisibleOnly: true option is mandatory — it tells the browser that every push message will result in a visible notification. The applicationServerKey is your VAPID public key, which identifies your server to the push service.
9 · Workbox Configuration Patterns
Workbox is Google's library that wraps the service worker APIs with production defaults. It handles cache management, versioning, routing, and plugin configuration — so you do not have to write raw service worker code for common patterns.
sw.jsjavascript
// sw.js — production Workbox setupimport { precacheAndRoute } from "workbox-precaching";import { registerRoute } from "workbox-routing";import { StaleWhileRevalidate, NetworkFirst, CacheFirst,} from "workbox-strategies";import { ExpirationPlugin } from "workbox-expiration";import { CacheableResponsePlugin } from "workbox-cacheable-response";// Pre-cache all webpack-generated assetsprecacheAndRoute(self.__WB_MANIFEST);// Google Fonts — Cache First, 1 year expiryregisterRoute( ({ url }) => url.origin === "https://fonts.googleapis.com" || url.origin === "https://fonts.gstatic.com", new CacheFirst({ cacheName: "google-fonts", plugins: [ new CacheableResponsePlugin({ statuses: [0, 200] }), new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 365 }), ], }),);// Images — Stale While Revalidate, 30 items maxregisterRoute( ({ request }) => request.destination === "image", new StaleWhileRevalidate({ cacheName: "images", plugins: [new ExpirationPlugin({ maxEntries: 30 })], }),);// API calls — Network First, 5 second timeoutregisterRoute( ({ url }) => url.pathname.startsWith("/api/"), new NetworkFirst({ cacheName: "api-cache", networkTimeoutSeconds: 5, plugins: [new CacheableResponsePlugin({ statuses: [0, 200] })], }),);
Key Workbox features used in this configuration:
workbox-precaching
Automatically generates a cache manifest with content hashes. Handles versioning — when a hash changes, the old entry is replaced.
workbox-routing
Declarative URL matching. Routes are evaluated in order — first match wins. Supports regex, string, and function matchers.
workbox-strategies
CacheFirst, NetworkFirst, StaleWhileRevalidate, CacheOnly, NetworkOnly. Each strategy is a pre-built, battle-tested implementation.
workbox-expiration
Cache size and age limits. Prevents unbounded cache growth. Essential for image caches and API response caches.
workbox-cacheable-response
Only cache responses with specific status codes (e.g., 0 for opaque responses, 200 for success). Prevents caching error pages.
Tip
Workbox is the standard for production service workers. If you are building a new service worker today, start with Workbox rather than raw APIs. It eliminates entire classes of bugs — cache versioning mistakes, missing response cloning, and improper opaque response handling.
10 · Putting It All Together
A production service worker combines pre-caching, runtime caching strategies, offline fallback, background sync, and push notifications into a coherent architecture:
Install — Pre-cache App Shell
Cache the app shell, offline page, and critical CSS/JS during the install event. Fail if any asset fails.
Activate — Clean Old Caches
Delete caches from previous versions. Migrate data if needed. Claim all uncontrolled clients.
Fetch — CSS/JS → Cache First
Versioned assets with content hashes are served from cache instantly. Never hit the network for these.
Fetch — Images → Stale While Revalidate
Serve cached images immediately. Update the cache in the background. Limit to 30 entries.
Fetch — API → Network First
Try the network first. Fall back to cache when offline. 5 second network timeout.
Fetch — Navigation → Offline Fallback
Cache every visited page. Serve /offline.html when both network and cache fail.
Sync — Drain Mutation Queue
Background Sync fires when connectivity returns. Send queued mutations to the server in order.
Push — Deliver Notifications
Push message from server wakes the service worker. Show notification with actions. Handle click to open URL.
11 · Key Takeaways
If you remember only a few things from this article, make them these:
Service workers are programmable proxies
They intercept every HTTP request from controlled pages. The lifecycle (install → waiting → activate → fetch) is event-driven and must be understood to avoid confusing update behavior.
Match strategy to resource type
Cache First for versioned assets (CSS/JS/fonts), Network First for API responses, Stale While Revalidate for images. Never use one strategy for everything.
Always provide an offline fallback
The most common mistake. Without /offline.html, users see the browser's error page when they navigate offline. Pre-cache it during install.
Cache API for responses, IndexedDB for data
The Cache API stores HTTP responses. IndexedDB stores structured application data. Use both in tandem for a complete offline architecture.
Background Sync makes offline mutations reliable
Deferred actions survive tab closure. The browser guarantees the sync event fires when connectivity returns. Exponential backoff on failure.
Workbox eliminates boilerplate
Use workbox-precaching, workbox-routing, and workbox-strategies in production. They handle cache versioning, routing, and response cloning correctly.
The browser controls the lifecycle
Use self.skipWaiting() and self.clients.claim() to activate immediately on update. Version your cache names. Delete old caches during activation.