Home > database >  Firefox & Safari doesn't send custom http headers in Service Worker requests
Firefox & Safari doesn't send custom http headers in Service Worker requests

Time:09-27

In firefox and safari, custom headers doesn't send on fetch requests inside a service worker. But chrome works. (I added my custom header in Access-Control-Allow-Headers )

Code inside service worker:

fetch(Request, {
    headers: {
      'my-custom-header': 'a value'
    }
  });

My OPTIONS returns 204, and request mode is 'cors'. Also it is same origin request.

CodePudding user response:

(For same-origin requests, CORS doesn't come into play.)

I'm not able to reproduce the problem you describe; here's a live deployment of a site with a service worker that makes a request to the https://httpbin.org/#/Request_inspection/get_headers endpoint when it starts up, and logs the response back, indicating what request headers were received:

fetch('https://httpbin.org/headers', {
  headers: {'my-custom-header': 'a value'},
})
.then((response) => response.json())
.then((data) => console.log(data.headers));

In Chrome, Firefox, and Safari, I see the custom header returned along with the other headers that are sent by default by the browser.

You can play around with this and test out different scenarios by remixing https://glitch.com/edit/#!/valuable-nonchalant-pet?path=sw.js:3:81

CodePudding user response:

I figured out my mistake. I was passing Request object instead of URL. So I should have done this like below:

const request = new Request(event.request); 
request.headers.append(Headers.SW_REQUEST, 'true'); 
return fetch(request);
  • Related