S
SafeVibe.io
FeaturesHow It WorksPricingDocs
S
SafeVibe.io

The Guardrail for the Vibe Coding Era. Production-grade security for AI-generated code.

Product

  • Features
  • Pricing
  • Security
  • Documentation
  • Learn

Resources

  • Security Guides
  • Next.js Security
  • OWASP Top 10

Legal

  • Privacy Policy
  • Security Docs
  • Terms of Service

© 2026 SafeVibe.io. All rights reserved.

PrivacyTerms
  1. Home
  2. Learn
  3. How to Fix Cross-Site Request Forgery (CSRF) in Express
High SeverityA01:2021 - Broken Access ControlCWE-352

How to Fix Cross-Site Request Forgery (CSRF) in Express

Learn how to prevent and fix Cross-Site Request Forgery (CSRF) vulnerabilities in Express applications. Step-by-step guide with code examples, security checklists, and best practices.

In This Guide

  • What Is Cross-Site Request Forgery (CSRF)?
  • Why It Matters
  • How to Fix It in Express
  • Code Examples
  • Security Checklist
  • Express Security Tips

What Is Cross-Site Request Forgery (CSRF)?

Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user into submitting a request they did not intend to make. The attack exploits the fact that browsers automatically include cookies (including session cookies) with every request to a domain, regardless of the request's origin.

An attacker crafts a malicious page or email containing a request to the target application. When an authenticated user visits the attacker's page, their browser automatically sends the request along with valid session cookies. The target application cannot distinguish this forged request from a legitimate one. CSRF attacks can change email addresses, transfer funds, modify account settings, or perform any action the authenticated user is authorized to do.

The attack is particularly effective because it does not require the attacker to steal the user's credentials -- it simply leverages the existing authenticated session. Modern single-page applications using token-based authentication (like JWT in headers) are naturally resistant to CSRF since custom headers are not automatically attached to cross-origin requests, but cookie-based authentication remains vulnerable without explicit protections.

Why It Matters

CSRF attacks can have serious consequences because they execute actions with the full authority of the victim user. In financial applications, CSRF can initiate unauthorized transfers. In administrative panels, it can create new admin accounts or change security settings. Because the requests come from the legitimate user's browser with valid authentication, they are difficult to detect and trace. CSRF attacks are also easy to execute at scale -- an attacker can embed the malicious request in a popular website, forum post, or advertising network, potentially affecting thousands of users simultaneously.

How to Fix It in Express

Implement anti-CSRF tokens: generate a unique, unpredictable token for each user session and include it in every state-changing request. The server validates this token before processing the request. Use the SameSite cookie attribute (set to "Lax" or "Strict") to prevent cookies from being sent with cross-origin requests. Verify the Origin and Referer headers on the server side. Require re-authentication for sensitive operations like changing passwords or email addresses. Use framework-provided CSRF protection (Next.js Server Actions have built-in CSRF protection, Django includes CSRF middleware, Express has csurf). For APIs, prefer token-based authentication sent via custom headers rather than cookies.

Express-Specific Advice

  • Use `helmet` middleware for setting security headers (CSP, HSTS, X-Frame-Options, etc.) with sensible defaults.
  • Use `express-rate-limit` for rate limiting. Apply stricter limits to authentication endpoints and API routes.
  • Always use parameterized queries with your database driver. Never concatenate user input into SQL strings.
  • Validate request bodies using `express-validator`, Zod, or Joi middleware. Reject requests that do not match expected schemas.

Code Examples

Vulnerable: No CSRF token validation
// DANGEROUS -- no CSRF protection
app.post("/transfer", (req, res) => {
  const { to, amount } = req.body;
  transferFunds(req.user.id, to, amount);
  res.json({ success: true });
});
Secure: CSRF token middleware
import csrf from "csrf";
const tokens = new csrf();

// Generate token for forms
app.get("/transfer", (req, res) => {
  const secret = req.session.csrfSecret ||= tokens.secretSync();
  const token = tokens.create(secret);
  res.render("transfer", { csrfToken: token });
});

// Validate token on submission
app.post("/transfer", (req, res) => {
  if (!tokens.verify(req.session.csrfSecret, req.body._csrf)) {
    return res.status(403).json({ error: "Invalid CSRF token" });
  }
  transferFunds(req.user.id, req.body.to, req.body.amount);
  res.json({ success: true });
});

Express Security Checklist for Cross-Site Request Forgery (CSRF)

Verify CSRF protection is enabled for all state-changing endpoints in Express
Set SameSite attribute to 'Lax' or 'Strict' on all session cookies
Validate Origin and Referer headers on the server side
Require re-authentication for sensitive operations (password change, email change, fund transfers)
Use framework-provided CSRF protection rather than implementing custom solutions
Test CSRF protection by attempting cross-origin form submissions
Run SafeVibe's CSRF scan on your Express application

Express Security Best Practices

1

Use `helmet` middleware for setting security headers (CSP, HSTS, X-Frame-Options, etc.) with sensible defaults.

2

Use `express-rate-limit` for rate limiting. Apply stricter limits to authentication endpoints and API routes.

3

Always use parameterized queries with your database driver. Never concatenate user input into SQL strings.

4

Validate request bodies using `express-validator`, Zod, or Joi middleware. Reject requests that do not match expected schemas.

5

Use `cors` middleware with explicit origin allowlists. Never use `cors({ origin: '*' })` in production.

6

Disable the `X-Powered-By` header with `app.disable('x-powered-by')` or by using helmet.

7

Use `multer` or `busboy` for file uploads with strict file type and size limits. Store files outside the web root.

8

Implement proper error handling middleware that does not leak stack traces or internal details in production.

Scan Your Express App with SafeVibe

Stop guessing if your Express app is vulnerable to Cross-Site Request Forgery (CSRF). Run an automated penetration test in minutes and get actionable results.

Start Free Scan

Related Guides

Cross-Site Request Forgery (CSRF) in Other Frameworks

Next.jsReactVueNuxt
View all Cross-Site Request Forgery (CSRF) guides

More Express Security Guides

Cross-Site Scripting (XSS)SQL InjectionInsecure Direct Object References (IDOR)Broken Authentication
View all Express guides