Versioned Cache Keys
What You'll Learn
You'll learn how to use versioned cache names to safely manage multiple cache stores, coordinate updates, and cleanly remove outdated caches without breaking your app.
Why Versioning Matters
Think of your service worker caches like labeled storage boxes. Without version numbers, you'd have just "app-cache" forever—making it impossible to know which box contains old items versus new ones. When you update your site, you need a clean way to switch from the old cache to the new one and throw away obsolete resources.
How Versioned Cache Keys Work
Instead of using static names like 'my-app-cache', you add version identifiers:
const CACHE_VERSION = 'v2';
const CACHE_NAME = `my-app-${CACHE_VERSION}`;
// Result: 'my-app-v2'
During the install event, you create a new cache with the updated version:
self.addEventListener('install', event => {
event.waitUntil(
caches.open('my-app-v2').then(cache => {
return cache.addAll(['/index.html', '/styles.css', '/app.js']);
})
);
});
During the activate event, you delete old cache versions:
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(name => name.startsWith('my-app-') && name !== 'my-app-v2')
.map(name => caches.delete(name))
);
})
);
});
This pattern ensures users always get fresh resources after an update completes, while old caches remain available until the new service worker activates.
Key Takeaway:
Versioned cache keys let you safely create new caches during updates, then clean up old ones during activation—preventing conflicts and ensuring smooth transitions between app versions.