Node.js › Authentication & Authorization

What is CSRF (Cross-Site Request Forgery), and how do you protect a Node.js session-based application against it?

Intermediate

Answer

CSRF tricks a logged-in user's browser into unknowingly submitting a malicious request to a site where they're already authenticated (since the browser automatically attaches the relevant session cookie), potentially performing an unwanted action like transferring funds or changing an email address. Protection typically combines the SameSite cookie attribute (set to 'Strict' or 'Lax', preventing the cookie from being sent on most cross-site requests) with a CSRF token -- a unique, unpredictable value embedded in forms and verified server-side, which an attacker's forged request can't know or supply.
app.use(cookieParser());
const csrfProtection = csrf({ cookie: true });

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

app.post('/transfer', csrfProtection, (req, res) => {
  // request automatically rejected if the csrf token doesn't match
  processTransfer(req.body);
});
Real-world example A banking application sets its session cookie's SameSite attribute to 'Strict' and additionally requires a CSRF token on all state-changing (POST/PUT/DELETE) requests, so that even if a user visits a malicious site while logged in, that site cannot successfully trigger a funds transfer on the user's behalf.

Common follow-ups: Why is CSRF primarily a concern for cookie/session-based authentication and largely irrelevant for token-based APIs that don't rely on cookies?;What's the difference between SameSite=Strict and SameSite=Lax in terms of what cross-site requests they actually block?