Exchanging cookies with Fetch

Andrei Cacio
FineCoding
Published in
1 min readDec 29, 2017

Short and sweet: the fetch() function signature accepts either a Request object or a string which represents the url followed by a second init object as a second parameter. They both have a property called credentials which can accept the following options:

  • omit(default) — never send cookies
  • same-origin — only send cookies for same origin requests
  • include — always send cookies

By default, the credentials property is set to “omit” the cookies. This means that fetch will not exchange any cookies for your requests. In other words, if you have a session created with your server and you want to access some endpoints via fetch, and those endpoints expect a session cookie to be sent on your request, those requests will fail.

Example 1:

Using the second argument to override the credentials property

Example 2:

Passing a Request reference to the fetch function.

This looks simple but I for one lost a couple of hours trying to figure out why my fetch requests didn’t work.

--

--

Andrei Cacio
FineCoding

JavaScript Developer @ Evozon | proud speaker and co-organizer at JSHeroes Community Meetups #javascript #web