Handling Breaking Changes
You'll learn how to safely migrate data and caches when your service worker logic fundamentally changes.
The Problem
Sometimes you need to make breaking changes to your service worker—changes so significant that old cached data becomes incompatible. Maybe you've switched from storing simple strings to complex JSON objects, changed your API response format, or restructured your entire caching strategy. Unlike regular app updates, service workers can't just "restart fresh" without potentially breaking user experience or losing data.
Migration Strategies
Think of this like renovating a house while people still live in it. You need a plan to move furniture (data) safely.
Clean Slate Approach
The simplest strategy: delete everything old during the activate event and start fresh. Use a cache version bump that makes old cache names obsolete:
const CACHE_VERSION = 'v2'; // bumped from v1
const CACHE_NAME = `app-cache-${CACHE_VERSION}`;
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(names =>
Promise.all(
names.filter(name => name !== CACHE_NAME)
.map(name => caches.delete(name))
)
)
);
});
Graceful Migration
For critical data, read from old caches, transform it, write to new caches, then delete old ones. Check the version, migrate what's salvageable, and mark the migration complete with a flag in IndexedDB.
When to Use Each
Use clean slate for non-critical assets (images, scripts). Use graceful migration for user-generated content or complex IndexedDB data that users can't easily recreate.
Key Takeaway: Handle breaking service worker changes by either wiping old caches cleanly with version bumps, or reading-transforming-writing data before deletion to preserve critical information through the transition.