Enable withCredentials in Axios for CORS Requests
This article explains how to configure the
withCredentials option in the Axios HTTP client to send
cross-origin requests with cookies, authorization headers, and TLS
client certificates. It covers configuring the setting per request,
creating reusable Axios instances, applying global defaults, and
understanding the required backend CORS configurations.
What is
withCredentials?
By default, cross-site Access-Control requests do not include
credentials like cookies or HTTP authentication headers. Setting
withCredentials: true tells the browser to include these
credentials in cross-origin requests.
1. Enabling for a Single Request
Pass { withCredentials: true } in the request
configuration object as the last argument:
import axios from 'axios';
// GET request
axios.get('https://api.example.com/data', {
withCredentials: true
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
// POST request
axios.post('https://api.example.com/login', {
username: 'user',
password: 'password'
}, {
withCredentials: true
})
.then(response => console.log(response.data))
.catch(error => console.error(error));2. Enabling on an Axios Instance
If your application makes multiple requests to the same authenticated
API, create an Axios instance with withCredentials
enabled:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
});
// All requests using apiClient will automatically include credentials
apiClient.get('/profile');
apiClient.post('/settings', { theme: 'dark' });3. Enabling Globally for All Requests
To apply credentials to every Axios request across your application, update the global defaults:
import axios from 'axios';
axios.defaults.withCredentials = true;Required Backend Server Configuration
For withCredentials to work successfully in the browser,
the server handling the cross-origin request must return the following
HTTP response headers:
Access-Control-Allow-Credentials: true: Informs the browser that credentials are permitted.Access-Control-Allow-Origin: Must specify the exact requesting origin (e.g.,https://myfrontend.com). It cannot be the wildcard*when credentials are included.