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

Cache Expiration Policies

Configuring maxEntries and maxAgeSeconds to automatically expire old cached resources and limit cache size.

Cache Expiration Policies

You'll learn how to use maxEntries and maxAgeSeconds in Workbox to automatically clean up old cached resources and prevent unlimited cache growth.

Why Cache Expiration Matters

Without expiration policies, your service worker cache grows indefinitely. Every resource you cache stays there forever, consuming browser storage and potentially serving stale content. Cache expiration policies act like automatic housekeeping—they ensure your cache stays fresh and within size limits.

Think of your cache like a refrigerator: without throwing out old food, it eventually fills up with expired items you'll never use.

Configuring Expiration Policies

Workbox's ExpirationPlugin lets you set two key constraints:

  • maxEntries: The maximum number of cached items. When exceeded, the oldest entries are removed first (LRU: Least Recently Used).
  • maxAgeSeconds: How long a cached resource remains valid. Resources older than this are automatically deleted.

When you configure a caching strategy, you add the expiration plugin alongside it:

workbox.routing.registerRoute(
  ({request}) => request.destination === 'image',
  new workbox.strategies.CacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 50,        // Keep only 50 images
        maxAgeSeconds: 30 * 24 * 60 * 60  // 30 days
      })
    ]
  })
);

This configuration ensures your image cache never holds more than 50 images and none older than 30 days. If you cache a 51st image, the least-recently-used one gets deleted. Any image sitting unused for 30 days is automatically purged.

You can use one constraint or both together—whatever makes sense for your resource type.

Key Takeaway:
Use maxEntries and maxAgeSeconds in Workbox's ExpirationPlugin to automatically limit cache size and age, keeping storage usage under control and content reasonably fresh.