Cache Expiration and TTL
You'll learn how to automatically invalidate stale cached resources by implementing time-based expiration policies in your Service Worker.
The Core Idea
Cached resources don't stay fresh forever. Even with the best caching strategy, you need a mechanism to determine when cached content is too old to serve. Time-to-Live (TTL) is a duration after which a cached resource expires and should be refreshed. By storing timestamps alongside cached responses and checking them before serving, you ensure users don't see outdated content indefinitely.
Think of it like milk in a refrigerator: you write the purchase date on the carton and check it before pouring. If it's past the expiration date, you throw it out and buy fresh milk—even if the fridge technically still has milk.
Implementing TTL Logic
When caching responses, store metadata containing the cache timestamp:
// During fetch event
const response = await fetch(request);
const cache = await caches.open('my-cache-v1');
// Clone response and add timestamp header
const clonedResponse = response.clone();
const headers = new Headers(clonedResponse.headers);
headers.append('sw-cache-timestamp', Date.now().toString());
const timestampedResponse = new Response(clonedResponse.body, {
status: clonedResponse.status,
statusText: clonedResponse.statusText,
headers: headers
});
await cache.put(request, timestampedResponse);
Before serving cached content, validate freshness:
const cached = await cache.match(request);
if (cached) {
const cachedTime = cached.headers.get('sw-cache-timestamp');
const age = Date.now() - parseInt(cachedTime);
const MAX_AGE = 60 * 60 * 1000; // 1 hour TTL
if (age < MAX_AGE) {
return cached; // Still fresh
}
// Expired - fetch new version
}
Key Takeaway: Cache expiration with TTL ensures your PWA serves fresh content by comparing timestamps against configured age limits, automatically invalidating stale resources before they're served to users.