2

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!

daemon
  • 372
  • 1
  • 4
  • 24

1 Answers1

2

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;
  }
);
denov
  • 11,180
  • 2
  • 27
  • 43
Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • chrome complains - Uncaught (in promise) TypeError: Failed to execute 'set' on 'Headers': Headers are immutable – denov May 09 '19 at 03:18
  • @denov take look at another Jeff's answer: https://stackoverflow.com/a/30063346/2234964 that's possible way to avoid this error. – Artem S. Feb 07 '20 at 21:36