Course contentsShow
← Web Development
Lesson 817 of 2,98214. Browser StorageFree lesson

Cache Versioning Strategies

Implementing version-based cache names and cleanup patterns for safe cache updates.

Cache Versioning Strategies

You'll learn how to safely update cached resources without breaking your app by using version-based cache names and cleanup patterns.

When you update your website, you need a way to replace old cached files without disrupting users currently browsing. Cache versioning solves this by creating separate cache containers for each version of your app, then cleaning up old caches once the new version is active.

The Core Idea

Think of cache versioning like organizing books on shelves. Instead of replacing books while someone's reading them, you set up a new shelf with updated editions. Once everyone's switched to the new shelf, you remove the old one.

Version-Based Cache Names

When opening a cache, include a version identifier in the name:

const CACHE_VERSION = 'v1.0.2';
const CACHE_NAME = `my-app-${CACHE_VERSION}`;

// Open versioned cache
caches.open(CACHE_NAME).then(cache => {
  return cache.addAll(['/index.html', '/style.css', '/app.js']);
});

Each time you update your app, increment the version. This creates a new, separate cache without touching the old one.

Cleanup Pattern

After creating a new cache, delete outdated versions to free up storage:

// List all caches and remove old ones
caches.keys().then(cacheNames => {
  return Promise.all(
    cacheNames.map(cacheName => {
      if (cacheName !== CACHE_NAME) {
        return caches.delete(cacheName);
      }
    })
  );
});

This pattern ensures old caches don't accumulate indefinitely while keeping the current version safe.

When to Clean Up

Perform cleanup when your new service worker activates—after it's installed but before it takes control. This ensures users transition smoothly from old to new cached content.

Key Takeaway: Use version identifiers in cache names to create separate containers for each app version, then clean up old caches systematically to prevent storage bloat while ensuring safe updates.