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

Deleting Old Caches on Activation

Implement cache cleanup in the activate event to remove outdated cache versions.

Deleting Old Caches on Activation

What you'll learn: How to automatically clean up outdated cache versions when your service worker activates, preventing storage bloat and stale content issues.

The Problem with Leftover Caches

When you update your service worker and deploy a new cache version, the old caches don't automatically disappear. Over time, these orphaned caches accumulate, wasting storage space and potentially serving stale content if your code accidentally references them.

How It Works

The activate event in your service worker is the perfect moment to perform housekeeping. At this point, the new service worker is taking control, and any old caches are no longer needed. You can iterate through all existing caches, compare them against a whitelist of current versions, and delete anything outdated.

Think of it like spring cleaning: once you've moved into your new apartment (activation), you throw out boxes from your old place that you no longer need.

Implementation Pattern

const CURRENT_CACHE = 'my-site-v2';

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CURRENT_CACHE) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

This code retrieves all cache names, checks each against your current version, and deletes any that don't match. The event.waitUntil() ensures the service worker won't finish activating until cleanup completes.

Key Takeaway: Always delete outdated caches during the activate event to prevent storage bloat and ensure users get fresh content from your latest cache version—it's essential maintenance for production PWAs.