Skip to main content

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.

✓ 5 caching strategies ✓ Workbox setup ✓ Vite / Next.js integration ✓ Cache versioning

Caching Strategy Decision Matrix

Strategy Best For Freshness
Cache FirstStatic assets (JS, CSS, fonts, images)Stale until new SW
Network FirstAPI responses, user-specific dataAlways fresh (online)
Stale-While-RevalidateBlog posts, product pages, public APIFresh on next visit
Cache OnlyOffline app shellNever updates
Network OnlyAnalytics, payments, real-time dataAlways 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.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Related Articles

Mar 27, 2026 · 15 min read

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.

Mar 26, 2026 · 16 min read

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.

Mar 26, 2026 · 12 min read

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.

Apr 2, 2026 · 22 min read

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.

Apr 2, 2026 · 25 min read

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.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →