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 | import axios from 'axios' |
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 | import axios from 'axios' |
You can also set a baseURL
property to simplify your requests:
1 | import axios from 'axios' |
For React applications that use axios-hooks
, you can configure withCredentials
using the following code:
1 | import axios from 'axios' |
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