Securing Cookies with Axios HTTP Client

Sending cookies using the Axios HTTP client requires a comprehensive approach to client-side configuration and server-side coordination to prevent unauthorized data access, session hijacking, and Cross-Site Request Forgery (CSRF). This guide outlines the key security considerations you must evaluate when transmitting cookies with Axios, including credential management, CORS policies, secure cookie flags, and instance isolation.

1. Explicit Credential Handling (withCredentials)

By default, Axios does not send cross-origin cookies. To include cookies in cross-site requests, you must set the withCredentials option to true.

// Recommended: Scoped instance for authenticated endpoints
const apiClient = axios.create({
  baseURL: 'https://api.yourdomain.com',
  withCredentials: true,
});

2. Cross-Site Request Forgery (CSRF / XSRF) Defense

When cookies are used for authentication, browsers automatically attach them to outbound requests matching the target origin, leaving the application vulnerable to CSRF attacks.

The security of cookies transmitted via Axios largely depends on how those cookies are defined by the backend server via the Set-Cookie header.

4. Cross-Origin Resource Sharing (CORS) Configuration

When sending authenticated requests with Axios across different origins, the server must be strictly configured to handle credentials.

5. Preventing Cross-Site Scripting (XSS)

If an attacker executes malicious JavaScript within your application, they can make unauthorized requests through pre-configured Axios instances that automatically include credentials.