Service Worker Caching Guide
Service workers intercept network requests and serve assets from cache, enabling offline support and near-instant repeat visits. Choose the right caching strategy for each resource type.
Caching Strategy Decision Matrix
| Strategy | Best For | Freshness |
|---|---|---|
| Cache First | Static assets (JS, CSS, fonts, images) | Stale until new SW |
| Network First | API responses, user-specific data | Always fresh (online) |
| Stale-While-Revalidate | Blog posts, product pages, public API | Fresh on next visit |
| Cache Only | Offline app shell | Never updates |
| Network Only | Analytics, payments, real-time data | Always fresh |
Workbox Setup with Vite (vite-plugin-pwa)
npm install --save-dev vite-plugin-pwa workbox-window
Manual Service Worker (Simple Example)
// public/sw.js
const CACHE_VERSION = 'v2';
const STATIC_CACHE = `static-${CACHE_VERSION}`;
const PRECACHE_ASSETS = ['/', '/offline.html', '/styles.css', '/app.js'];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(STATIC_CACHE)
.then(cache => cache.addAll(PRECACHE_ASSETS))
.then(() => self.skipWaiting()) // Activate immediately
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys()
.then(keys => Promise.all(
// Delete old cache versions
keys.filter(k => k !== STATIC_CACHE).map(k => caches.delete(k))
))
.then(() => self.clients.claim()) // Take over all open tabs
);
});
self.addEventListener('fetch', event => {
// Cache First for static assets
if (PRECACHE_ASSETS.includes(new URL(event.request.url).pathname)) {
event.respondWith(
caches.match(event.request).then(r => r || fetch(event.request))
);
}
}); Update Notification Pattern
// main.ts — notify users of new version
import { registerSW } from 'virtual:pwa-register';
const updateSW = registerSW({
onNeedRefresh() {
if (confirm('New version available! Reload to update?')) {
updateSW(true);
}
},
onOfflineReady() {
console.log('App ready for offline use');
},
}); Frequently Asked Questions
What is a service worker and how does it enable caching?▼
A service worker is a JavaScript file that runs in a background thread, separate from the web page. It can intercept network requests and serve responses from a cache. Unlike HTTP caching (controlled by response headers), service worker caching is programmatic — you decide exactly what to cache, when to cache it, and what strategy to use. Service workers require HTTPS (or localhost) and are registered via `navigator.serviceWorker.register('/sw.js')`.
What are the main service worker caching strategies?▼
The five main strategies are: (1) Cache First — serve from cache, fall back to network (best for static assets). (2) Network First — try network, fall back to cache on failure (best for dynamic API data). (3) Stale-While-Revalidate — serve from cache immediately, update cache in background (best for user-facing content). (4) Cache Only — only serve from cache, never hit network (rare, for fully offline apps). (5) Network Only — bypass cache always (for analytics, billing, real-time data).
Should I write service workers manually or use Workbox?▼
Use Workbox (Google's service worker library) unless you have specific requirements. Manual service workers are error-prone — common mistakes include not versioning caches, not handling failed cache opens, and not properly managing scope. Workbox provides battle-tested strategies, automatic precaching of build assets (via workbox-webpack-plugin or vite-plugin-pwa), background sync, and TypeScript types. Manual is appropriate for learning or very simple, static offline pages.
How do I update a service worker when I deploy new assets?▼
Service workers update automatically when the sw.js file changes (even by one byte). For precaching with Workbox, change the cache version or update the precache manifest (auto-generated by build plugins). When a new SW installs, it doesn't activate until all pages using the old SW are closed. Use `skipWaiting()` in the new SW and `clients.claim()` in the activate event to take over immediately. Notify users with a 'New version available, reload?' prompt for major updates.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
LLM Prompt Caching Calculator
Calculate cost savings from LLM prompt caching. Compare Anthropic Claude and OpenAI GPT-4 caching pricing. Estimate monthly savings based on call volume and cache hit rate.
Open free tool →
Web Performance Checklist
Interactive web performance checklist covering images, fonts, JavaScript, CSS, caching, and server. Check off items to track your score out of 100 and export as Markdown.
Open free tool →
PWA Manifest Generator
Generate a valid Web App Manifest (manifest.json) for your Progressive Web App. Configure name, icons, display mode, theme colors, and orientation. Download ready-to-use JSON.
Open free tool →
More Free Tools
Related Articles
Building Production-Ready PWAs with Workbox in 2026
Complete guide to Progressive Web Apps with Workbox in 2026. Master Service Worker lifecycle, caching strategies, offline-first patterns, Web App Manifest, and push notifications. Real code examples included.
Caching Strategies for Web Developers: Browser, CDN, Server-Side, and Database
Complete guide to web caching strategies. Covers HTTP cache headers, CDN configuration, Redis/Memcached patterns, service workers, and database query caching with practical code examples and performance benchmarks.
Progressive Web Apps Complete Guide 2026: Service Workers, Offline-First, and Beyond
The definitive PWA guide for 2026. Learn service workers, Web App Manifest, offline-first strategies, push notifications, installability, and how PWAs compare to native apps—with real code examples.
CDN and Edge Caching 2026: Complete Guide to Content Delivery Networks and Edge Computing
Comprehensive guide to CDN and edge caching strategies for 2026. Covers Cloudflare, Fastly, Akamai, AWS CloudFront, edge functions, cache invalidation, real-time synchronization, and multi-CDN strategies with code examples.
Performance Optimization 2026: Complete Guide to Frontend, Backend, and Infrastructure
Comprehensive performance optimization guide for 2026 covering Core Web Vitals, JavaScript bundle optimization, server-side rendering, caching strategies, database query optimization, CDN configuration, and real-world benchmarks.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →