Set Cookies when making an Axios request in JS and Node

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
4 min

banner

# Set Cookies when making an Axios request in JS and Node

You can set the withCredentials property to true in the configuration object to set cookies when making an Axios HTTP request.

When the withCredentials property is set to true, axios makes the HTTP request using credentials.

index.js
import axios from 'axios'; async function getUser() { try { const response = await axios.get( 'https://randomuser.me/api/', // ๐Ÿ‘‡๏ธ set withCredentials to `true` { withCredentials: true, }, ); return response.data; } catch (err) { console.log(err); } } console.log(await getUser());

set cookies when making axios request

The code for this article is available on GitHub

Notice that we set the withCredentials property to true in the Request Config object.

When withCredentials is true, cross-site Access-Control requests are made using credentials such as cookies, authorization headers or TLS client certificates.

The syntax for making an HTTP request with the cookies included is as follows.

index.js
// ๐Ÿ‘‡๏ธ HTTP GET request axios.get('YOUR_URL', {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP POST request axios.post('YOUR_URL', data, {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP PUT request axios.put('YOUR_URL', data, {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP PATCH request axios.patch('YOUR_URL', data, {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP DELETE request axios.delete('your_url', {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP OPTIONS request axios.options('your_url', {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP HEAD request axios.head('your_url', {withCredentials: true});
The code for this article is available on GitHub

Notice that the request config object comes after the data argument when making a POST, PUT or PATCH HTTP request.

You can read more about the withCredentials property in this section of the MDN docs.

The boolean property indicates whether Access-Control requests should be made using credentials (cookies and authorization headers) or not.

The property only applies when making requests to a different origin.

Responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true when making the request.

In other words, when the withCredentials property is set to true, axios sends cookies and other credentials automatically.

The cookies honor the same-origin policy and are not accessible through document.cookie or from the response headers.

When the withCredentials setting is set to true, the Access-Control-Allow-Origin header cannot be set to a wildcard *.

Instead, the header has to be set to one or more, specific domains.

# Setting the withCredentials property globally

You can also set the withCredentials property in your global axios defaults config.

index.js
axios.defaults.withCredentials = true

setting with credentials property globally

The config defaults are applied to every request.

However, you might not want to set the withCredentials property on all requests, especially if you make axios requests to different domains.

In this case, you can create a custom instance.

index.js
// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com', withCredentials: true, }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
The code for this article is available on GitHub

Then you would use the instance to make HTTP requests.

index.js
instance.get('/users')

# Adding the Set-Cookie header to the exposed headers in Express

One way to try to access the Set-Cookie header when using Express.js is to include the header in the list of exposed headers.

index.js
import express from 'express'; import cors from 'cors'; // ๐Ÿ‘‡๏ธ using commonJS require() syntax // const express = require('express') // const cors = require('cors') const app = express(); const corsOptions = { origin: [ 'http://localhost:3000', 'http://127.0.0.1', 'http://example.com', // your origins here ], credentials: true, exposedHeaders: ['set-cookie'], }; app.use(cors(corsOptions));
The code for this article is available on GitHub

You can also only set the CORS options object for a single route.

index.js
app.use('/users', cors(corsOptions), router);

When issuing the axios request, make sure you have withCredentials set to true.

index.js
// ๐Ÿ‘‡๏ธ HTTP GET request axios.get('YOUR_URL', {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP POST request axios.post('YOUR_URL', data, {withCredentials: true}); // ๐Ÿ‘‡๏ธ HTTP PUT request axios.put('YOUR_URL', data, {withCredentials: true});

The exposedHeaders property configures the Access-Control-Expose-Headers CORS header.

The header adds the specified headers to the list of allowed headers and enables you to access them in JavaScript Code in browsers.

For example, if Access-Control-Expose-Headers is set as follows.

shell
Access-Control-Expose-Headers: X-My-Custom-Header, Set-Cookie

Then, the 2 specified headers are going to be exposed to the browser.

# Explicitly setting the Cookie header

You can also set the headers property in the config object when making an axios request.

index.js
// ๐Ÿ‘‡๏ธ HTTP GET request axios.get('YOUR_URL', { Cookie: 'cookie1=value; cookie2=value; cookie3=value;' }); // ๐Ÿ‘‡๏ธ HTTP POST request axios.post('YOUR_URL', data, { Cookie: 'cookie1=value; cookie2=value; cookie3=value;' });
The code for this article is available on GitHub

The Cookie HTTP request header contains the stored HTTP cookies that are associated with the server.

These are cookies that the server previously sent using the Set-Cookie header.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev