/ #JavaScript #fetch 

Pass cookies with axios or fetch requests

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 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

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).

Table of Contents

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
})

transport
  .get('/cookie-auth-protected-route')
  .then(res => res.data)
  .catch(err => { /* not hit since no 401 */ })

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

axios
  .get(
    '/cookie-auth-protected-route',
    { withCredentials: true }
  )
  .then(res => res.data)
  .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:

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

unsplash-logoAlex

Looking for a new job? Take Triplebyte’s quiz and have top tech companies pitch you!

Author

Hugo Di Francesco

A Software Engineer and recovering Frontend Engineer who is big on Node.js, queues and Vue(s). He shares practical JavaScript tips for the developer who wants to get things done on Code with Hugo. University College London (UCL), MEng Mathematical Computation Graduate.

Subscribe for Enterprise Node.js and JavaScript Guides

Build your web platform with modern Node.js/JavaScript best-practices, tools and patterns