Selective Caching with Request Filtering
What you'll learn: How to programmatically decide which requests deserve a spot in your cache based on URL patterns and request properties.
The Core Idea
Not every request should be cached. Images and CSS? Probably yes. API calls with user-specific data? Maybe not. Third-party analytics scripts? Definitely not. Selective caching means writing logic in your service worker's fetch event handler to inspect incoming requests and decide whether to cache them based on criteria like URL structure, HTTP method, or request destination.
Think of it like a bouncer at an exclusive club—not every request gets through the velvet rope into your cache.
Filtering Requests
Inside your fetch event listener, you can examine the request object before deciding to cache:
self.addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
// Only cache same-origin GET requests
if (request.method !== 'GET' || url.origin !== self.location.origin) {
event.respondWith(fetch(request));
return;
}
// Skip caching API endpoints
if (url.pathname.startsWith('/api/')) {
event.respondWith(fetch(request));
return;
}
// Cache static assets only
if (url.pathname.match(/\.(css|js|png|jpg|svg|woff2)$/)) {
event.respondWith(
caches.match(request).then(cached => {
return cached || fetch(request).then(response => {
return caches.open('static-v1').then(cache => {
cache.put(request, response.clone());
return response;
});
});
})
);
}
});
This pattern lets you apply different caching strategies to different resource types, preventing cache bloat and avoiding privacy issues with personalized content.
Key Takeaway: Selective caching uses conditional logic to filter which requests enter your cache based on URL patterns, HTTP methods, and request properties—preventing inappropriate or excessive caching while maximizing offline utility.