How to force credentials to every Axios request

By

Learn how to send credentials and cookies with every Axios request by setting withCredentials: true, and how to apply it globally with axios.create().

~~~

To send cookies with every Axios request, create an instance with axios.create({ withCredentials: true }) and use that instance everywhere. Let’s see why you need this, and how it works.

I was using Axios to interact with an API that set a JWT token.

The API returned the token in a cookie and I quickly figured I needed to set withCredentials: true in the Axios options:

import axios from 'axios'

axios.post(API_SERVER + '/login', { email, password }, { withCredentials: true })

Otherwise the cookie would not be saved.

Why does this happen?

In the browser, cross-origin requests don’t send or store cookies by default. My frontend ran on one origin, the API on another, so the browser dropped the cookie the API tried to set.

withCredentials: true tells the browser to include credentials (cookies, in this case) in the cross-origin request, and to accept cookies from the response.

I also needed to set it for every other request I made, to send the JWT token to the server:

axios.get(API_SERVER + '/todos', { withCredentials: true })

How do you set it once, for all requests?

Now, it’s ok for a few requests, but for many, you’d probably like to use a general configuration.

You can do it using the create() method to create a new Axios instance you’ll then use in your requests:

import axios from 'axios'

const instance = axios.create({
  withCredentials: true
})

instance.get(API_SERVER + '/todos')

It’s also common to add a baseURL property:

import axios from 'axios'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER
})

instance.get('todos')

Every request made through instance now carries the cookie. No option to repeat, no request to forget.

One thing to watch out for

Setting withCredentials on the client is not enough. The server must also allow it.

The API has to respond with the Access-Control-Allow-Credentials: true header, and Access-Control-Allow-Origin must be the exact origin of your frontend. A wildcard * does not work with credentials, the browser rejects the response.

If your cookies still don’t show up, check those two headers first. That’s where the problem was, every time it happened to me.

What about axios-hooks?

In React I used axios-hooks, and to configure withCredentials I used this code:

import axios from 'axios'
import useAxios, { configure } from 'axios-hooks'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER,
})

configure({ instance })

const [{ data, loading, error }, refetch] = useAxios('todos')

The configure() call makes every useAxios() hook in the app use our instance, so the credentials setting applies everywhere.

~~~

Related posts about js: