Search code examples
javascriptservice-workerworkbox

StaleWhileRevalidate: Remove from cache once a non-success status is encountered


We’re using Workbox’s StaleWhileRevalidate strategy to cache responses of a JSON API. Under normal circumstances, this API will respond with a status code of 200 and deliver the desired data.

However, it might happen that a user should no longer have access to that data. In that case, our JSON API responds with status 401.

Unfortunately, our app still “sees” the cached JSON response.

Are there any settings or hooks in Workbox which I could use to prune a cached entry, once we encounter a 401? Or is there any other advice or best practice to follow?


Solution

  • I'd recommend writing a custom plugin that used the cacheWillUpdate callback, and took appropriate action if the status of the incoming Response is 401. (workbox-cacheable-response uses cacheWillUpdate under the hood, but you need more flexibility, so writing your own logic makes sense.)

    Something like:

    // Or use workbox.core.cacheNames.runtime for the default cache.
    const cacheName = 'my-api-cache';
    
    const myPlugin = {
      cacheWillUpdate: async ({response}) => {
        if (response.status === 401) {
          const cache = await caches.open(cacheName);
          await cache.delete(response.url);
          return null;
        }
    
        // Add in any other checks here, if needed.
        return response;
      },
    };
    
    workbox.routing.registerRoute(
      /^\/api\/data.json$/,
      new workbox.strategies.StaleWhileRevalidate({
        cacheName,
        plugins: [myPlugin],
      })
    );