JavaScript Service Worker Offline Caching for PWA
Serve your web app offline with Service Workers and the Cache API: precaching, runtime caching strategies and a fallback page.
Overview
A user opens your app in a tunnel, on a plane, or on hotel Wi-Fi that drops every thirty seconds — and instead of your interface they get the browser’s error page. A Service Worker prevents that. It registers from your page, then runs in its own thread where it intercepts every request the app makes and answers from a cache you control.
The recipe below covers the full setup: registering the worker from main.js, precaching an app shell during install, three runtime strategies (cache-first, network-first, stale-while-revalidate), deleting stale caches on activate, an offline fallback page, and replaying a form submission with Background Sync. Everything is plain JavaScript — no framework and no Workbox required.
When to Use
Reach for a Service Worker when your app should keep working without a reliable connection:
- Repeat visits should render instantly even on slow networks: a cached asset beats the network every single time.
- You’re building an installable PWA and offline support is part of the deal.
- Mobile users on flaky connections hit your app daily, and a blank screen costs you them.
- Your origin serves the same static files over and over and you want the client to absorb that traffic.
Skip it when the content can’t tolerate any staleness: live dashboards, stock tickers, account balances. A stale cached answer is worse than an honest error in those cases. Server-rendered sites that always serve per-user data gain little either. You would cache the shell but still need the network for the body. And remember the hard requirement: Service Workers only register on a secure context, so HTTPS in production or localhost while developing.
Solution
Register a service worker
The page registers /sw.js once, inside the load event so registration doesn’t compete with first paint. If the browser doesn’t support workers, nothing breaks — the if guard makes offline support a progressive enhancement.
// main.js
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/sw.js")
.then((reg) => console.log("SW registered:", reg.scope))
.catch((err) => console.error("SW registration failed:", err));
});
}
Cache-first strategy for static assets
Precache the app shell during install, then answer every GET from cache before touching the network. Note the .catch() at the end: for navigation requests it returns the offline page, and for failed sub-resources it returns Response.error() so the fetch rejects like a normal network failure. Returning undefined there would make respondWith() throw instead.
// sw.js
const CACHE_NAME = "app-v1";
const STATIC_ASSETS = [
"/",
"/index.html",
"/styles.css",
"/app.js",
"/offline.html",
"/favicon.ico"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(STATIC_ASSETS))
.then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => {
return Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
);
})
.then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
event.respondWith(
caches.match(event.request).then((cached) => {
if (cached) return cached;
return fetch(event.request)
.then((response) => {
if (!response || response.status !== 200) return response;
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, clone);
});
return response;
})
.catch(() => {
if (event.request.mode === "navigate") {
return caches.match("/offline.html");
}
return Response.error();
});
})
);
});
Stale-while-revalidate strategy
The fastest perceived strategy: serve the cached copy right away, and refresh the cache in the background for the next visit. Users occasionally see the previous version for one load. Acceptable for assets that change often but not critically.
// sw.js
const CACHE_NAME = "swr-v1";
self.addEventListener("install", () => {
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(
keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))
))
.then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
event.respondWith(
caches.open(CACHE_NAME).then((cache) => {
return cache.match(event.request).then((cached) => {
const fetchPromise = fetch(event.request)
.then((response) => {
if (response && response.status === 200) {
cache.put(event.request, response.clone());
}
return response;
})
.catch(() => cached);
return cached || fetchPromise;
});
})
);
});
Network-first for API data with cache fallback
API responses should stay fresh, so try the network first and quietly write successful answers into a dedicated cache. When the network drops, the user gets the last known-good response, or a clean JSON error if nothing was cached yet.
// sw.js
const API_CACHE = "api-v1";
const STATIC_CACHE = "static-v1";
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (event.request.method !== "GET") return;
if (url.pathname.startsWith("/api/")) {
event.respondWith(
fetch(event.request)
.then((response) => {
if (response.status === 200) {
const clone = response.clone();
caches.open(API_CACHE).then((cache) => {
cache.put(event.request, clone);
});
}
return response;
})
.catch(() => {
return caches.match(event.request).then((cached) => {
if (cached) return cached;
return new Response(
JSON.stringify({ error: "Offline" }),
{ headers: { "Content-Type": "application/json" } }
);
});
})
);
return;
}
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request).then((response) => {
const clone = response.clone();
caches.open(STATIC_CACHE).then((cache) => {
cache.put(event.request, clone);
});
return response;
}).catch(() => caches.match("/offline.html"));
})
);
});
Cache cleanup on activation
Every deploy that bumps CACHE_NAME leaves the previous cache behind. The activate handler is the right place to delete anything not on the allowlist: it runs once, after the old worker steps aside.
self.addEventListener("activate", (event) => {
const allowedCaches = ["static-v2", "api-v2"];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (!allowedCaches.includes(cacheName)) {
console.log("Deleting old cache:", cacheName);
return caches.delete(cacheName);
}
})
);
}).then(() => self.clients.claim())
);
});
Background sync for offline form submission
When the user submits a form offline, store the payload locally, register a sync event, and let the worker replay it once connectivity returns. If the browser lacks SyncManager (Safari doesn’t implement it), the code falls back to a normal fetch.
// main.js
async function submitForm(data) {
if ("serviceWorker" in navigator && "SyncManager" in window) {
const reg = await navigator.serviceWorker.ready;
await storeFormData(data);
reg.sync.register("submit-form");
} else {
await fetch("/api/submit", {
method: "POST",
body: JSON.stringify(data)
});
}
}
// sw.js — load helpers first: importScripts("/db.js")
self.addEventListener("sync", (event) => {
if (event.tag === "submit-form") {
event.waitUntil(replayFormSubmission());
}
});
async function replayFormSubmission() {
const stored = await getStoredFormData();
for (const data of stored) {
const res = await fetch("/api/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await removeStoredFormData(data.id);
}
}
The storeFormData, getStoredFormData and removeStoredFormData helpers need a real store. localStorage isn’t reachable from a worker, so IndexedDB does the job: a minimal implementation looks like this:
// db.js — shared: <script> in the page, importScripts("/db.js") in sw.js
function openDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open("offline-forms", 1);
req.onupgradeneeded = () =>
req.result.createObjectStore("queue", { keyPath: "id", autoIncrement: true });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function storeFormData(data) {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction("queue", "readwrite");
tx.objectStore("queue").add(data);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
async function getStoredFormData() {
const db = await openDB();
return new Promise((resolve, reject) => {
const req = db.transaction("queue", "readonly")
.objectStore("queue").getAll();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function removeStoredFormData(id) {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction("queue", "readwrite");
tx.objectStore("queue").delete(id);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
One detail worth noticing in replayFormSubmission: fetch only rejects on network failure, not on HTTP errors. The res.ok check keeps a 500 from deleting a queued record. The sync event will simply fire again later and retry.
Explanation
A Service Worker is a programmable proxy that lives between your page and the network. Once registered it runs in a separate thread — no DOM access, no localStorage — and every request from controlled pages passes through its fetch handler, where you decide whether the answer comes from cache, network, or a fallback.
The lifecycle has four phases that matter:
- Install fires on first registration (and on every update). This is where you precache the app shell with
cache.addAll(): one failed fetch aborts the whole install, so keep the list to what the page truly needs.skipWaiting()lets the new worker jump straight past the waiting phase. - Activate fires after install, once no old worker controls a client. Delete outdated caches here and call
clients.claim()so the worker takes over open tabs immediately instead of waiting for the next load. - Fetch fires for every request the page makes. Check
event.requestand pick the strategy that fits: static assets get cache-first, API calls get network-first, frequently changing assets get stale-while-revalidate. - Sync fires when connectivity returns after
reg.sync.register(). The browser may fire it even after the page closed (that’s the point) but Safari never implemented it, so treat it as progressive enhancement.
The strategies differ mostly in what they sacrifice:
- Cache-first trades freshness for speed. Perfect for hashed or versioned assets; dangerous for an unversioned
app.js, which will serve stale code untilCACHE_NAMEchanges. - Network-first keeps data fresh and quietly keeps a fallback copy. The cost is paying network latency on every online request even when a cached answer exists.
- Stale-while-revalidate serves the cached copy instantly and revalidates in the background: best perceived speed, but the user sees the previous version until the next load.
Three things bite teams in production:
Storage quota. The Cache API shares the origin quota with IndexedDB and other storage. You can inspect it with navigator.storage.estimate(), and under pressure the browser may evict the whole origin’s data. navigator.storage.persist() asks for durable storage (Chrome grants it based on engagement). This is why the precache list should stay small: a failed or bloated addAll() slows every install.
Opaque responses. Cross-origin requests answered without CORS — CDN fonts, third-party widgets — come back as opaque responses with status 0 and an unreadable body. The status === 200 checks in the examples deliberately skip caching them. You can cache opaque responses (they replay fine), but they inflate your quota and you can’t validate what you’re storing — the same kind of expiring-storage trade-off covered in the LocalStorage TTL expiration recipe, just with less visibility.
Updates and TTL. Browsers byte-compare sw.js on navigations (at most once every 24 hours) and install the new worker when the bytes differ. The old worker keeps control until its last client closes. That’s why skipWaiting() and clients.claim() exist, and why bumping CACHE_NAME on every deploy matters: the activate handler only cleans caches that don’t match the new allowlist.
If maintaining a hand-rolled worker grows into a project of its own, look at Workbox: Google’s library wraps all of these strategies, generates the precache manifest at build time, and handles versioning for you. The concepts are the same ones shown here. For the server-side equivalent of this trade-off (check the store first, then the origin) the cache-aside pattern is the same idea applied to backend data.
Variants
Pick per request type, not per app: a single worker usually combines several of these:
| Strategy | Best for | Freshness | Offline |
|---|---|---|---|
| Cache-first | Static assets (CSS, JS, fonts) | Low | Full |
| Network-first | API data, dynamic content | High | Fallback |
| Stale-while-revalidate | Images, fonts, frequent updates | Medium | Full |
| Cache-only | Offline pages, precached shell | None | Full |
| Network-only | Analytics, non-cacheable calls | High | None |
What Works
- Precache only what the app shell can’t render without:
offline.html, core CSS and JS. A giantaddAll()list fails on the first missing file and slows every install. - Match the strategy to the data: cache-first for assets that carry a hash or version in the URL, network-first for anything a user expects to be current.
- Delete old caches in
activate, always. Skipped cleanups quietly grow storage until the quota eviction hits. Browsers evict the whole origin, not one cache at a time. - Guard the
fetchhandler withevent.request.method !== "GET". POST/PUT/DELETE must go to the network untouched, and caching their responses is wrong anyway. - Give navigations a real offline page. A styled
offline.htmlwith a retry link reads infinitely better than the browser’s error screen. - Version cache names (
static-v1→static-v2) on every deploy that changes cached content; the activate cleanup then does the migration for free. - During development,
skipWaiting()+clients.claim()plus DevTools’ “Update on reload” saves you from wondering why the old worker is still alive.
Common Mistakes
- Not versioning cache names, so users stay on stale content forever. The worker updates but nothing invalidates what it cached.
- Precaching too much in
install: every entry inSTATIC_ASSETSis a network request, and one404aborts the entire install. - Falling through without a response. If the
.catch()in a fetch handler doesn’t return aResponse(or a promise of one),respondWith()throws: always return the offline page orResponse.error(). - Caching POST or other non-GET responses. They aren’t idempotent, and the Cache API will throw on a
cache.put()for non-GET anyway. - Caching opaque responses by accident and wondering where the quota went. You can’t inspect them, only trust them.
- Assuming Background Sync is universal. Safari never shipped
SyncManager; feature-detect it or iOS users silently lose the offline queue. - Forgetting HTTPS. Registration only works on secure contexts:
localhostis exempt, a staging domain over plain HTTP isn’t.
See Also
- Using Service Workers — MDN: the canonical walkthrough of registration, lifecycle and debugging.
- Cache API — MDN: full reference for
caches.open,match,putand quota behavior. - Service worker caching and HTTP caching — web.dev: how the SW cache interacts with
Cache-Controlheaders. - Workbox — Chrome for Developers: when a hand-rolled worker outgrows its welcome.
- For the bigger picture, see the Progressive Web Apps (PWA) — Complete Guide.
- Runnable companion code: a minimal PWA demo with the worker, IndexedDB queue and offline fallback wired together.
Frequently Asked Questions
How do I force the service worker to update?
Bump the cache version (static-v1 → static-v2) and change a byte in sw.js. The browser detects the difference on the next navigation, installs the new worker, and (if you called skipWaiting() and clients.claim()) the activate handler clears the old caches immediately instead of waiting for tabs to close.
Can service workers access localStorage?
No — workers have no window and no localStorage. Inside the worker your options are the Cache API for HTTP responses or IndexedDB for structured data (the db.js helpers above use exactly that).
How do I debug a service worker?
Chrome DevTools → Application → Service Workers shows registered workers, lets you unregister, and has "Update on reload" plus "Bypass for network" toggles. The Console tab surfaces the worker's logs.
What is the difference between skipWaiting and clients.claim?
skipWaiting() runs inside install and tells the new worker to activate without waiting for open tabs to close. clients.claim() runs inside activate and makes that active worker control existing tabs right away. You typically want both for instant updates.
Can I test offline behavior without going offline?
Yes: Chrome DevTools → Network → Offline checkbox simulates a dropped connection. For automated coverage, Playwright's context.setOffline(true) does the same thing inside CI.
Related Resources
JavaScript Infinite Scroll Pagination
Implement scroll-based data loading in JavaScript with IntersectionObserver: sentinel detection, fetch, loading and error states, and clean teardown.
RecipeJavaScript LocalStorage with TTL Expiration
Store data in browser localStorage with TTL expiration: expiry wrappers, lazy cleanup, quota handling, stale-while-revalidate and cross-tab sync
RecipeJavaScript Drag and Drop File Upload with HTML5 API
Implement native HTML5 drag and drop file upload in JavaScript — drop zones, file validation, upload progress and image previews without libraries.
GuideProgressive Web Apps (PWA) — Complete Guide
A thorough guide to building Progressive Web Apps: service workers, offline support, Web App Manifest, push notifications, and installability.
PatternCache-Aside Pattern
Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.