Course contentsShow
← Web Development
Lesson 2426 of 2,98243. Service Workers Deep DiveFree lesson

Cache Versioning Strategies

Learn how to version your service worker caches to manage updates and prevent stale content issues.

Cache Versioning Strategies

What you'll learn: How to systematically version your service worker caches to manage updates cleanly and avoid serving stale content when your app changes.

Why Cache Versioning Matters

Imagine your service worker caches are like storage containers in your garage. When you renovate your house, you need new containers and a plan to replace the old ones. Without a versioning strategy, old caches pile up, waste space, and might accidentally serve outdated content even after you've deployed new versions.

The Core Concept

Cache versioning means assigning unique identifiers (usually version numbers or timestamps) to your cache names. When your service worker updates, it creates new caches with new names, leaving old caches intact until you're ready to delete them.

Typical pattern:

const CACHE_VERSION = 'v2';
const STATIC_CACHE = `static-${CACHE_VERSION}`;
const RUNTIME_CACHE = `runtime-${CACHE_VERSION}`;

When you update your site, you increment the version:

const CACHE_VERSION = 'v3'; // Changed!

Now your new service worker uses static-v3 and runtime-v3, while the old v2 caches remain temporarily. During the activate event, you clean up old versions:

self.addEventListener('activate', event => {
  const currentCaches = [STATIC_CACHE, RUNTIME_CACHE];
  event.waitUntil(
    caches.keys().then(names => 
      Promise.all(
        names.filter(name => !currentCaches.includes(name))
             .map(name => caches.delete(name))
      )
    )
  );
});

This ensures users get fresh content without conflicts between old and new cached resources.

Key Takeaway: Cache versioning using unique identifiers per release lets you deploy updates safely, control exactly when old content is removed, and prevent cache conflicts between service worker versions.