Skip to main content

How to Handle Cookies in Axios (Browser and Node.js)

When working with APIs that use cookies for authentication or session management, you need to ensure that your Axios requests are configured correctly. The method you use depends entirely on whether your code is running in a web browser (e.g., a React app) or in a Node.js server environment, as these two platforms handle cookies very differently.

This guide will teach you the correct way to handle cookies in both environments, covering the essential withCredentials setting for browsers and manual header management for Node.js.

Scenario 1: In the Browser (Cross-Origin Requests)

In a browser environment, you cannot manually set the Cookie header for security reasons. Instead, the browser automatically manages cookies for you.

However, if your frontend (e.g., http://localhost:3000) is making a request to a different domain (e.g., http://api.example.com), the browser will not send or receive cookies by default. This is a security feature known as the Same-Origin Policy.

The Solution: withCredentials: true

To tell the browser to include cookies in a cross-origin request, you must set the withCredentials property to true in your Axios request configuration.

import axios from 'axios';

// For a GET request
axios.get('https://api.example.com/user', {
withCredentials: true // This is the key setting
})
.then(response => {
console.log('Request successful', response.data);
});

// For a POST request (notice it's the third argument)
axios.post('https://api.example.com/login', { username: 'user', password: 'password' }, {
withCredentials: true
});
note

You can also set this globally if all your requests need credentials:

axios.defaults.withCredentials = true;

Server-Side Requirements (CORS)

Setting withCredentials: true on the client is only half the battle. Your backend server must also be configured to accept these credentials. It must send the following CORS headers in its response:

  1. Access-Control-Allow-Credentials: true: This header must be present and set to true.
  2. Access-Control-Allow-Origin: This header cannot be a wildcard (*). It must be set to the exact origin of your frontend application (e.g., http://localhost:3000).

If the server is not configured this way, the browser will block the request, even if you set withCredentials: true.

In a Node.js environment, there is no browser to automatically manage cookies for you. You must manually read the Set-Cookie headers from responses and manually send Cookie headers in subsequent requests.

Sending Cookies Manually

You can set the Cookie header directly in the Axios configuration.

const axios = require('axios');

axios.get('https://api.example.com/data', {
headers: {
// Manually set the Cookie header string
'Cookie': 'sessionId=12345; preferences=darkmode'
}
})
.then(response => {
console.log(response.data);
});

Manually parsing and sending cookies in Node.js can get complicated quickly. The professional solution is to use a library like axios-cookiejar-support along with tough-cookie. This combination adds automatic, browser-like cookie management to your Node.js Axios instance.

Solution:

  1. Install the libraries: npm install axios touch-cookie axios-cookiejar-support
  2. Configure Axios:
const axios = require('axios');
const { wrapper } = require('axios-cookiejar-support');
const { CookieJar } = require('tough-cookie');

const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));

// This request will automatically store any received cookies in the 'jar'
await client.post('https://api.example.com/login', { username: 'user', password: 'password' });

// This subsequent request will automatically send the stored cookies from the 'jar'
const response = await client.get('https://api.example.com/profile');

Sometimes you might want to read the Set-Cookie header in your frontend JavaScript code. By default, this header is hidden from client-side code for security.

To make it visible, your server must explicitly expose it using the Access-Control-Expose-Headers CORS header.

Server-Side Configuration (e.g., Express with cors middleware):

app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
exposedHeaders: ['set-cookie'] // Allow the browser to see this header
}));
note

Even with this setting, many modern browsers will still hide HttpOnly cookies from JavaScript for security reasons, which is generally a good thing.

Conclusion

Handling cookies in Axios requires knowing your environment.

  • In the Browser: Do not try to set headers manually. Instead, use withCredentials: true to ask the browser to handle cookies for you. Ensure your server's CORS configuration allows this.
  • In Node.js: You must manage cookies yourself. For simple cases, you can manually set the Cookie header. For complex sessions, use a dedicated library like axios-cookiejar-support to get browser-like automatic cookie management.