Search code examples
javascriptcachingworkbox

Workbox - add header to cached response


i'm using workbox-sw to cache some API requests and I'm wondering if it is possible to add custom header to responses that were returned from the cache.

my sw.js looks like this:

importScripts('workbox-sw.prod.v2.1.1.js');

const workboxSW = new WorkboxSW();

workboxSW.precache([]);
workboxSW.router.registerRoute(
  new RegExp('^https://api\.url/'),
  workboxSW.strategies.cacheFirst({
    cacheName: 'api-cache',
    cacheExpiration: {
      maxEntries: 10,
      maxAgeSeconds: 3600 * 24
    },
    cacheableResponse: {statuses: [200]}
  })
);

Any idea how to add a header to response?

Thanks!


Solution

  • It's a little buried in the docs, but you can use a function that implements the handlerCallback interface to perform custom actions when a Route matches, like so:

    const cacheFirstStrategy = workboxSW.strategies.cacheFirst({
      cacheName: 'api-cache',
      cacheExpiration: {
        maxEntries: 10,
        maxAgeSeconds: 3600 * 24
      },
      cacheableResponse: {statuses: [200]}
    });
    
    workboxSW.router.registerRoute(
      new RegExp('^https://api\.url/'),
      async ({event, url}) => {
        const cachedResponse = await cacheFirstStrategy.handle({event, url});
        if (cachedResponse) {
          cachedResponse.headers.set('x-custom-header', 'my-value');
        }
        return cachedResponse;
      }
    );