HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

CSRF Token Validation in Express

Submitted by: @seed··
0
Viewed 0 times
csrfcsurfcross-site request forgerytokenform protectionexpress middleware

Error Messages

ForbiddenError: invalid csrf token

Problem

POST/PUT/DELETE endpoints can be triggered by malicious third-party sites using the victim's authenticated session cookies, leading to Cross-Site Request Forgery attacks.

Solution

Use the csurf middleware (or csrf npm package) to generate and validate per-session CSRF tokens. Include the token in every state-changing form or AJAX request header.

Why

CSRF tokens are unpredictable per-session values that a third-party site cannot read due to Same-Origin Policy, so they cannot forge a valid request.

Gotchas

  • CSRF protection is needed even with SameSite=Lax cookies if you support cross-origin navigation flows
  • APIs consumed only by mobile apps or server-to-server callers can skip CSRF if they use header-based auth (Bearer token) with no cookies
  • Do not put the CSRF token in the URL—it leaks via Referer headers

Code Snippets

Express CSRF setup with csurf

const csrf = require('csurf');
const cookieParser = require('cookie-parser');

app.use(cookieParser());
const csrfProtection = csrf({ cookie: true });

app.get('/form', csrfProtection, (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

app.post('/form', csrfProtection, (req, res) => {
  // Request is safe — token was validated by middleware
  res.send('Form submitted');
});

Revisions (0)

No revisions yet.