Sébastien Rosset
Sébastien Rosset

Reputation: 1531

How to add fetch options to Workbox?

I need to add credentials: 'same-origin' to all fetch requests in order to make a PWA work in a password-protected website. Otherwise if I leave the website and come back later, the browser doesn't ask for my password and returns an Unauthorized error.

How do I do that with Workbox ? I noticed the RequestWrapper class includes fetchOptions, but I can't find a way to use them.

Upvotes: 1

Views: 1809

Answers (2)

Sébastien Rosset
Sébastien Rosset

Reputation: 1531

Thanks to Jess Posnick for the answer. To avoid rewriting all workbox strategies, I ended up using a custom plugin:

const addFetchOptionsPlugin = {
  requestWillFetch: ({ request }) => new Request(request, { 
    credentials: 'same-origin', redirect: 'follow'
  })
};

workbox.router.registerRoute(
  new RegExp('my-route'),
  workbox.strategies.cacheFirst({
    cacheName: 'my-cache',
    plugins: [addFetchOptionsPlugin]
  })
);

Upvotes: 1

Jeff Posnick
Jeff Posnick

Reputation: 56104

In v2, precaching should already set credentials: 'same-origin' as the FetchOptions on all outgoing requests.

For runtime caching, you can get this behavior by constructing your own RequestWrapper instance and passing that in to the runtime caching handler you're using:

const requestWrapper = new RequestWrapper({
  cacheName: 'my-cache-name', // Change this for each separate cache.
  fetchOptions: {
    credentials: 'same-origin',
  },
  plugins: [], // Add any plugins you need here, e.g. CacheExpiration.
});

const staleWhileRevalidateHandler = new StaleWhileRevalidate({requestWrapper});

workboxSW.router.registerRoute(
  new RegExp('/path/prefix'),
  staleWhileRevalidateHandler
);

(I'm not sure how you're using the Workbox libraries, but you may need to explicitly import additional scripts to get access to the RequestWrapper class, like https://unpkg.com/[email protected]/build/importScripts/workbox-runtime-caching.prod.v2.0.3.js)

Upvotes: 2

Related Questions