CSRF (Cross-Site Request Forgery)

The attacker's site makes the victim's browser send a request to your app. The browser adds the cookies automatically, so the request is authenticated.

<!-- on evil.com -->
<form action="https://bank.com/transfer" method="POST">
  <input name="to" value="attacker"><input name="amount" value="10000">
</form>
<script>document.forms[0].submit()</script>

Who is at risk? Apps that authenticate with cookies. APIs that use Authorization: Bearer <token> headers are not affected, because browsers don't add those automatically.

Packages

PackageUse
csrf-csrfDouble-submit-cookie CSRF tokens (maintained)
csrf-syncSynchronizer-token pattern (session based)
cookie-parserNeeded to read cookies

csurf is deprecated. Don't use it.

✅ Defense 1: SameSite cookies (easiest, do it always)

res.cookie('sid', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax', // 'strict' is even safer but breaks links from other sites
});

✅ Defense 2: CSRF token

const { doubleCsrf } = require('csrf-csrf');
const { generateCsrfToken, doubleCsrfProtection } = doubleCsrf({
  getSecret: () => process.env.CSRF_SECRET,
  getSessionIdentifier: (req) => req.session.id,
});

app.get('/csrf-token', (req, res) => res.json({ token: generateCsrfToken(req, res) }));
app.use(doubleCsrfProtection); // checks the x-csrf-token header on POST/PUT/PATCH/DELETE

✅ Defense 3: check Origin

app.use((req, res, next) => {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
  if (req.get('origin') !== process.env.APP_ORIGIN) return res.status(403).end();
  next();
});

Checklist

  • SameSite=Lax or Strict on session cookies
  • CSRF tokens for cookie-based state-changing requests
  • GET requests never change state
  • CORS does not allow * together with credentials (see 10-security-headers-and-cors)