How to Share Cookies Across Subdomains in Axios

Sharing cookies across subdomains when using the Axios HTTP client requires proper configuration across both the backend server and the frontend client. To successfully send and receive session or authentication cookies between origins like app.example.com and api.example.com, you must scope the cookie to the parent domain on the server, configure Cross-Origin Resource Sharing (CORS) headers properly, and explicitly tell Axios to include credentials with requests.

By default, cookies set by a server are only accessible to the exact domain that issued them. To make a cookie accessible across all subdomains, the backend must specify the parent domain in the Set-Cookie header.

Example of an HTTP response header from the server:

Set-Cookie: sessionId=abc123xyz; Domain=.example.com; Path=/; Secure; HttpOnly; SameSite=Lax

2. Configure Backend CORS Headers

Because requests between subdomains are treated as cross-origin requests, the receiving API server must explicitly authorize the requesting origin and allow credentials.

  1. Access-Control-Allow-Origin: Specify the exact requesting subdomain (e.g., https://app.example.com). You cannot use the wildcard * when credentials are used.
  2. Access-Control-Allow-Credentials: Set this header to true.

Example Express.js configuration:

const cors = require('cors');

app.use(cors({
  origin: 'https://app.example.com',
  credentials: true
}));

3. Enable Credentials in Axios

On the frontend, Axios does not send cross-site cookies by default. You must enable the withCredentials option either on a specific request or globally across an Axios instance.

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  withCredentials: true // Automatically sends cookies on all requests
});

export default apiClient;

Option B: Per-Request Configuration

import axios from 'axios';

axios.get('https://api.example.com/user/profile', {
  withCredentials: true
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Request failed', error);
});

4. Local Development Setup

Subdomain cookie sharing cannot be tested directly using localhost because browsers treat localhost as a single host without standard subdomain resolution.

To test locally:

  1. Map custom domains in your local hosts file (/etc/hosts on macOS/Linux or C:\Windows\System32\drivers\etc\hosts on Windows):
    127.0.0.1 app.localtest.me
    127.0.0.1 api.localtest.me
  2. Set the cookie domain to .localtest.me on your local backend.
  3. Access your application via http://app.localtest.me:3000.