29

I'm playing around with window.fetch() in Firefox and Chrome. For some reasons, fetch() doesn't send any cookies. Now that wouldn't be a problem, as I can send them using

fetch('/something', { headers: { Cookie: document.cookie } })

But this won't work for httpOnly cookies.

Damian Senn
  • 1,135
  • 1
  • 9
  • 13

2 Answers2

63

Okay, I found out after reading on the Mozilla Developer Network a bit more and trying out the credentials option.

Looks like the credentials option is what I should have looked for.

fetch('/something', { credentials: 'same-origin' }) // or 'include'

Will send the cookies.

Damian Senn
  • 1,135
  • 1
  • 9
  • 13
  • 12
    Here is the MDN article. - https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials `'omit'` is the default, and doesn't send any cookies. `'same-origin'` will send cookies if the endpoint lives on the same uri. `'include'` will send cookies to all uris. – Yoshua Wuyts Jun 27 '15 at 09:52
  • Just ran into this, thank a lot! Helped me out a ton. – Sean Newell Jul 11 '17 at 18:00
  • 2
    In recent browsers 'same-origin' become the default value, but it can be explicitely written for back compatibility. In Firefox, this default value is from version 61 (released 26 June 2018). – Seb35 Jan 28 '19 at 14:48
  • Does this mean `same-origin` or `include` imply httpOnly? – Robin Wieruch Aug 24 '19 at 14:57
  • @YoshuaWuyts seems like 'same-origin' is the default now. – Robin Wieruch Aug 24 '19 at 14:58
  • 2
    This will still not work for httpOnly cookies and that is good. – Nagabhushan Baddi Nov 17 '19 at 12:23
2

There are three points here:

  1. If you're making a cross-origin request, set the Access-Control-Allow-Credentials: true. So that the server accepts your cookies.

  2. Set the credentials options either to include for cross-origin requests or same-origin for same-origin requests

  3. Set the credentials option of fetch on both requests that you retrieve and send the cookie