Blog>
Snippets

Custom Caching Strategy with a Service Worker

Set up a service worker to cache API responses and control the cache behavior for repeat visits.
const CACHE_NAME = 'api-cache-v1';
const API_ENDPOINT = '/api/data';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      // Precaching can be done here if needed
    })
  );
});
This code defines the cache name and the API endpoint that will be cached. The install event handler is used to perform necessary operations when the service worker is installed, such as opening a cache where API responses will be stored. Precaching is optional and can be added here if needed.
self.addEventListener('fetch', (event) => {
  if (event.request.url.includes(API_ENDPOINT)) {
    // Only handle API requests
    event.respondWith(
      caches.match(event.request).then((response) => {
        // Serve from cache if possible
        return response || fetch(event.request).then((fetchResponse) => {
          return caches.open(CACHE_NAME).then((cache) => {
            // Clone and store the fetch response in the cache and return the fetch response
            cache.put(event.request, fetchResponse.clone());
            return fetchResponse;
          });
        });
      })
    );
  }
});
This code sets up a fetch event listener to handle API requests. When a fetch occurs, it checks if the request URL includes the API endpoint. If it does, it tries to serve the response from the cache. If the cache doesn't contain the response, it fetches it from the network, caches the response for future use, and then serves it.
self.addEventListener('activate', (event) => {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            // Delete old caches not present in the whitelist
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
This code activates the new version of the service worker. It ensures that any old, outdated caches are deleted by comparing the existing cache names against a whitelist array that contains the current cache names to be kept.