Last Updated:

What is the Difference Between X-XSRF-TOKEN and X-CSRF-TOKEN? When to Use Hidden Fields vs Headers Explained

Cross-Site Request Forgery (CSRF) is a malicious attack where an attacker tricks a user into performing unintended actions on a trusted website. For example, an attacker could force a logged-in user to transfer funds, change account settings, or delete data—all without the user’s knowledge. To mitigate CSRF attacks, developers use CSRF tokens (or XSRF tokens, where "XSRF" is an alternative abbreviation for CSRF).

But confusion often arises around token naming conventions (e.g., X-XSRF-TOKEN vs. X-CSRF-TOKEN) and delivery methods (hidden fields vs. HTTP headers). Are these tokens technically different? When should you use a hidden field versus a header?

This blog demystifies these concepts, explaining the purpose of CSRF tokens, the origin of naming differences, and practical guidelines for choosing between hidden fields and headers.

Table of Contents#

  1. Introduction to CSRF and CSRF Tokens
  2. What Are X-XSRF-TOKEN and X-CSRF-TOKEN?
  3. Key Differences Between X-XSRF-TOKEN and X-CSRF-TOKEN
  4. Hidden Fields vs. Headers: When to Use Which?
  5. Practical Examples
  6. Best Practices for CSRF Protection
  7. Conclusion
  8. References

Introduction to CSRF and CSRF Tokens#

What is CSRF?#

CSRF exploits the trust a website has in a user’s browser. When a user logs into a site like bank.com, their browser stores authentication cookies (e.g., session IDs). An attacker’s malicious site (evil.com) can then send a request to bank.com (e.g., a funds transfer) using the user’s stored cookies. Since bank.com recognizes the user’s cookies, it processes the request as legitimate.

How CSRF Tokens Stop Attacks#

CSRF tokens are unique, random values generated by the server and associated with the user’s session. The token is included in the user’s request (via a hidden field or header). The server validates that the token in the request matches the token stored in the user’s session. Since attackers cannot access the user’s session or predict the token, they cannot forge valid requests.

What Are X-XSRF-TOKEN and X-CSRF-TOKEN?#

X-XSRF-TOKEN and X-CSRF-TOKEN are naming conventions for CSRF tokens, not technical standards. They serve the exact same purpose (preventing CSRF attacks) but are named differently based on:

  • The web framework or library in use.
  • Whether the token is transmitted via a hidden field or an HTTP header.

Origin of the Names#

  • X-CSRF-TOKEN: Often used when the token is embedded in a hidden form field (e.g., Django, Ruby on Rails) or sent via a header (e.g., Django’s X-CSRFToken header).
  • X-XSRF-TOKEN: Common in JavaScript-heavy applications (e.g., Angular, React) where the token is stored in a cookie and sent via an HTTP header.

No technical difference exists between the two names. They are simply labels chosen by developers or frameworks to identify the CSRF token.

Key Differences Between X-XSRF-TOKEN and X-CSRF-TOKEN#

While the tokens themselves are functionally identical, their naming conventions correlate with differences in how and where they are used. The table below summarizes these distinctions:

FeatureX-CSRF-TOKENX-XSRF-TOKEN
Naming OriginPopularized by server-side frameworks (e.g., Django, Rails, Laravel).Popularized by client-side frameworks (e.g., Angular, React with Axios).
Common Storage- Hidden HTML form fields (e.g., Django’s csrfmiddlewaretoken).
- Cookies (e.g., Django’s csrftoken cookie).
- Stored in a cookie (e.g., Angular’s XSRF-TOKEN cookie).
Transmission Method- Hidden field in form data (for HTML form submissions).
- HTTP header (for AJAX requests).
Exclusively sent via an HTTP header (e.g., X-XSRF-TOKEN).
Typical Use CaseTraditional web apps with HTML forms (e.g., login/signup forms).Single-page applications (SPAs) using AJAX/API calls (e.g., React/Angular apps).

Hidden Fields vs. Headers: When to Use Which?#

The choice between hidden fields and headers depends on the type of request and the application architecture.

When to Use Hidden Fields#

Hidden fields embed the CSRF token directly in an HTML form. When the form is submitted (via a button click), the browser automatically includes the token in the request body.

Best for:

  • Traditional HTML Form Submissions: For example, a login form, checkout form, or user profile update form.
  • Applications with Minimal JavaScript: If your app relies on server-rendered HTML (e.g., Django, Rails) and does not use heavy client-side scripting.
  • Form Data (application/x-www-form-urlencoded): Hidden fields naturally fit into form data payloads.

Example Workflow:

  1. Server generates a CSRF token and embeds it in a hidden field:
    <form action="/transfer-funds" method="POST">  
      <input type="hidden" name="csrfmiddlewaretoken" value="random-token-123">  
      <input type="text" name="amount" placeholder="Amount">  
      <button type="submit">Transfer</button>  
    </form>  
  2. User submits the form; the browser sends csrfmiddlewaretoken=random-token-123 in the request body.
  3. Server validates the token against the user’s session.

When to Use Headers#

Headers send the CSRF token in the HTTP request headers (e.g., X-CSRF-TOKEN or X-XSRF-TOKEN). This method is ideal for JavaScript-driven requests (AJAX/API calls) where data is sent in formats like JSON.

Best for:

  • AJAX/API Requests: Apps using XMLHttpRequest, fetch, or libraries like Axios to send data (e.g., SPAs).
  • JSON Payloads: When sending data in application/json format (hidden fields are not easily included in JSON bodies).
  • Cross-Domain Requests (with CORS): Headers work with CORS (Cross-Origin Resource Sharing) if configured properly.

Example Workflow:

  1. Server stores the CSRF token in a cookie (e.g., XSRF-TOKEN=random-token-123).
  2. Client-side JavaScript reads the cookie and sends the token in a header:
    // Using fetch API  
    fetch("/api/update-profile", {  
      method: "POST",  
      headers: {  
        "Content-Type": "application/json",  
        "X-XSRF-TOKEN": document.cookie.split("XSRF-TOKEN=")[1].split(";")[0] // Extract token from cookie  
      },  
      body: JSON.stringify({ name: "John Doe" })  
    });  
  3. Server reads the X-XSRF-TOKEN header and validates it against the session.

Practical Examples#

Example 1: Hidden Field (Django Form)#

Django, a Python framework, uses hidden fields for CSRF protection in forms.

Template Code:

<!-- Django template with CSRF token -->  
<form method="post">  
  {% csrf_token %} <!-- Renders a hidden input: <input type="hidden" name="csrfmiddlewaretoken" value="..."> -->  
  <label for="username">Username:</label>  
  <input type="text" id="username" name="username">  
  <button type="submit">Submit</button>  
</form>  

Request Payload:
When submitted, the form sends:

csrfmiddlewaretoken=random-django-token&username=johndoe  

Example 2: Header (Angular + X-XSRF-TOKEN)#

Angular automatically handles XSRF protection by default.

How Angular Works:

  • The server sets a cookie named XSRF-TOKEN with the CSRF token.
  • Angular reads this cookie and sends it in the X-XSRF-TOKEN header for all POST/PUT/DELETE requests.

Server (Node.js/Express) Setup:

// Set XSRF-TOKEN cookie  
app.use(csrf({ cookie: true }));  
app.get("/", (req, res) => {  
  res.cookie("XSRF-TOKEN", req.csrfToken()); // Send token in cookie  
  res.render("index");  
});  

Angular HTTP Request:

// Angular service (automatically includes X-XSRF-TOKEN header)  
import { HttpClient } from "@angular/common/http";  
 
constructor(private http: HttpClient) {}  
 
updateProfile() {  
  return this.http.post("/api/profile", { name: "John Doe" });  
}  

Best Practices for CSRF Protection#

Regardless of whether you use X-XSRF-TOKEN, X-CSRF-TOKEN, hidden fields, or headers, follow these best practices:

  1. Always Validate Tokens on the Server: Client-side validation is useless—attackers can bypass it.
  2. Use Secure Cookies: Store tokens in cookies with the Secure flag (only sent over HTTPS) and SameSite=Lax or SameSite=Strict (prevents cross-origin cookie sending).
  3. Avoid HttpOnly for Header Tokens: If using headers, the cookie must be readable by JavaScript (so omit HttpOnly). For hidden fields, HttpOnly is safe.
  4. Rotate Tokens Periodically: Regenerate tokens after a session expires or after sensitive actions (e.g., password changes).
  5. Don’t Rely on Referer/Origin Headers: These headers can be spoofed or missing (e.g., in privacy-focused browsers). Use them as secondary checks, not primary.

Conclusion#

X-XSRF-TOKEN and X-CSRF-TOKEN are interchangeable naming conventions for CSRF tokens. The real distinction lies in how the token is transmitted:

  • Hidden fields for traditional HTML form submissions.
  • Headers for AJAX/API requests in JavaScript-heavy apps.

By understanding these conventions and choosing the right delivery method, you can effectively protect your application from CSRF attacks. Always validate tokens on the server and follow security best practices to ensure robust protection.

References#