Back to docs
Recipe

Service Worker Patterns

Offline-first caching, background sync, and push notification strategies for resilient web applications.

Cache-First Strategy

Intercept all network requests and serve from caches.open('v1') before falling back to the network. Ideal for static assets that rarely change — JS bundles, CSS, and font files.

Network-First with Timeout

Race a network fetch against a cache read with a configurable deadline. If the network wins within 3 seconds, update the cache and return the fresh response. Otherwise, serve the stale cached version to keep the UI responsive.

Background Sync Queue

Register a sync event listener to replay failed POST requests when connectivity returns. Store pending mutations in IndexedDB and drain the queue inside the sync handler — the browser retries automatically.

Push Notification Lifecycle

Subscribe via pushManager.subscribe() with a VAPID public key. Store the subscription endpoint on your server. On push receipt, call self.registration.showNotification() with title, body, icon, and a data payload for click routing.

Update Flow

Listen for the install event to pre-cache critical resources. On activate, purge old cache entries and claim uncontrolled clients with clients.claim(). Post a message to all open windows so the UI can prompt the user to refresh.

Pro tip: Always version your cache keys. Increment the version string on every deploy to avoid serving stale HTML shells that reference deleted chunk hashes.