Search code examples
progressive-web-appsworkbox

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.


Solution

  • 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/workbox-runtime-caching@2.0.3/build/importScripts/workbox-runtime-caching.prod.v2.0.3.js)