Blog>
Snippets

Network-first with Fallback to Cache

Demonstrate how to implement a network-first strategy that falls back to the cache if the network request fails, ideal for applications where fresh data is a priority.
if ('caches' in window) {
  // This code will check for cache availability in the browser
}
First, we check if the Cache Storage API is available in the browser.
function fetchAndCache(request) {
  return fetch(request)
    .then(response => {
      if (!response.ok) {
        throw Error('Network response was not ok.');
      }
      const responseToCache = response.clone();
      caches.open('my-cache').then(cache => {
        cache.put(request, responseToCache);
      });
      return response;
    })
    .catch(() => caches.match(request));
}
This function attempts a network request and caches the response. If the network request fails, it will try to retrieve the response from the cache.
self.addEventListener('fetch', event => {
  event.respondWith(
    fetchAndCache(event.request).catch(() => {
      return caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }
        // Optional: Return a default fallback page for certain requests
        if (event.request.mode === 'navigate') {
          return caches.match('/offline.html');
        }
      });
    })
  );
});
This event listener intercepts fetch events, calls the fetchAndCache function, and handles cases where both the network and the cache fail. Optionally, it provides a fallback for navigation requests.