GoogleChrome / workbox

📦 Workbox: JavaScript libraries for Progressive Web Apps
https://developers.google.com/web/tools/workbox/
MIT License
12.21k stars 801 forks source link

Credentials missing in navigate requests #3336

Open jarkt opened 2 weeks ago

jarkt commented 2 weeks ago

Library Affected: workbox-strategies

Browser & Platform: Google Chrome 126 for Android and surely other versions

Issue or Feature Request Description: I've noticed a behavior of Chrome that seems to be inconsistent and leads to a problem that I can't solve using the workbox way. When a service worker is installed and I open a tab with the app, credentials (cookies in this case) are "inside" the request. But this is not the case when the PWA is installed as an Android app. In this case the initial call is without credentials. I'm not sure if this is correct from CORS rules or a bug in Chrome, but it doesn't matter. That's why I've added this code to my service worker (I haven't configured any other runtime caching yet):

registerRoute(
  () => true,
  new NetworkOnly({
    fetchOptions: {
      credentials: 'include',
    }
  })
)

But it has no effect, because options of "navigate" requests are not passed to the fetch function: https://github.com/GoogleChrome/workbox/blob/v7/packages/workbox-strategies/src/StrategyHandler.ts#L201

This was my test code to see that credentials=include would solve my problem, which it does:

self.addEventListener('fetch', (event) => {
  const request = event.request.clone()

  event.respondWith(
    fetch(request, {
      credentials: 'include'
    })
  )
})

I don't know why the options are not passed. Can I solve the problem in another way?

jarkt commented 2 weeks ago

Perhaps this code at the top of the service worker is a workable solution without causing conflicts with some workbox functions like pre- or runtime caching:

self.addEventListener('fetch', (event) => {
  if (event.request.mode === "navigate") {
    event.respondWith(
      fetch(event.request, {
        credentials: 'include'
      })
    )
  }
})