How Axios Protects Against CSRF Attacks

Axios provides built-in mechanisms to defend against Cross-Site Request Forgery (CSRF/XSRF) attacks by automating the implementation of the Synchronizer Token Pattern. This article explains how Axios reads anti-CSRF tokens stored in cookies, automatically attaches them as custom HTTP request headers, and provides configuration options to adapt to various backend frameworks.

The Default CSRF Protection Mechanism

Cross-Site Request Forgery occurs when a malicious website tricks a user's browser into executing unwanted actions on a trusted site where the user is currently authenticated. Browsers automatically attach cookies to cross-origin requests, allowing attackers to exploit existing sessions.

To counter this, modern web applications use anti-CSRF tokens. Axios natively supports this pattern through a standardized two-step process:

  1. Reading the Cookie: On client-side requests, Axios automatically looks for a cookie named XSRF-TOKEN.
  2. Setting the Header: If the cookie exists, Axios reads its value and appends it as an HTTP request header named X-XSRF-TOKEN.

Because the browser's Same-Origin Policy prevents unauthorized third-party domains from reading cookies set by your application, a malicious site cannot read the token value to set the required header. When the backend receives the request, it compares the header value against the session or cookie value to verify authenticity.

Customizing Token and Header Names

Different backend frameworks (such as Django, Ruby on Rails, or Spring Boot) often use different naming conventions for CSRF cookies and headers. Axios allows you to customize these values using the xsrfCookieName and xsrfHeaderName properties.

You can configure them globally:

import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken'; // Example for Django
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

Or within a specific Axios instance:

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  xsrfCookieName: '_csrf',
  xsrfHeaderName: 'X-CSRF-Token',
});

Cross-Origin Request Handling

By default, Axios only sends the XSRF header to requests sharing the same origin (protocol, domain, and port) as the client application. If your frontend and API are hosted on different domains, you must explicitly enable cross-origin credentials:

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  withCredentials: true,
});

When withCredentials is set to true, the browser sends cookies with cross-origin requests, allowing Axios to read and attach the necessary CSRF headers provided that Cross-Origin Resource Sharing (CORS) is properly configured on the server.

Security Considerations and Limitations

While Axios handles the client-side execution of CSRF token forwarding, robust protection depends on several backend configurations: