/

How to Force Credentials for Every Axios Request

How to Force Credentials for Every Axios Request

In this blog post, we will discuss how to force credentials for every Axios request. Axios is a popular JavaScript library used for making HTTP requests. When interacting with an API that sets a JWT token, it is important to ensure that the token is sent with every request. By default, Axios does not send credentials with requests, so we need to set the withCredentials option to true.

To set withCredentials for a single request, you can use the following code:

1
2
3
import axios from 'axios'

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

This will save the JWT token in a cookie. To send the token with subsequent requests, you need to set withCredentials: true for each request:

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

However, setting withCredentials for every request can become repetitive and cumbersome. To avoid this, you can create a new Axios instance with the create() method and set the withCredentials option:

1
2
3
4
5
6
7
import axios from 'axios'

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

instance.get(API_SERVER + '/todos')

You can also set a baseURL property to simplify your requests:

1
2
3
4
5
6
7
8
import axios from 'axios'

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

instance.get('todos')

For React applications that use axios-hooks, you can configure withCredentials using the following code:

1
2
3
4
5
6
7
8
9
10
11
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')

By following these steps, you can ensure that credentials are forced for every Axios request, allowing you to securely interact with APIs that require a JWT token.

Tags: Axios, HTTP requests, JWT token, withCredentials, create(), baseURL, axios-hooks