DEV Community

Cover image for Pass cookies with axios or fetch requests

Pass cookies with axios or fetch requests

Hugo Di Francesco
Developer, JavaScript, CSS and web. Writing at Code with Hugo.
Originally published at on ・2 min read

When sending requests from client-side JavaScript, by default cookies are not passed.

By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests

Two JavaScript HTTP clients I use are axios, a “Promise based HTTP client for the browser and Node.js” and the fetch API (see Fetch API on MDN).

Pass cookies with requests in axios

In axios, to enable passing of cookies, we use the withCredentials: true option.

Which means we can create a new axios instance with withCredentials enabled:

const transport = axios.create({
  withCredentials: true

  .then(res =>
  .catch(err => { /* not hit since no 401 */ })

It’s also possible to set it in the request options:

    { withCredentials: true }
  .then(res =>
  .catch(err => { /* not hit since no 401 */ })

Or override the global defaults:

axios.defaults.withCredentials = true

Pass cookies with requests using fetch

The equivalent with fetch is to set the credentials: 'include' or credentials: 'same-origin' option when sending the request:

  { credentials: 'include' } // could also try 'same-origin'
).then(res => {
  if (res.ok) return res.json()
  // not hit since no 401

Download free do whatever you want high-resolution photos from Alex

Discussion (1)

abbiranjan profile image
Alok Ranjan

Nice one.