QA
Intermediate LevelExpress JS

How do you defend Express endpoints against Cross-Site Request Forgery (CSRF) attacks?

❓ Interview Prompt: Explain Cross-Site Request Forgery (CSRF), SameSite cookie defense, double-submit cookie pattern, and csrf-csrf package.

CSRF (Cross-Site Request Forgery) occurs when an attacker's website tricks a victim's browser into executing unwanted state-changing actions (like submitting a form) on your site where the victim is currently authenticated.

Defense Strategies:

1
SameSite Cookies ('SameSite=Strict / Lax'): Modern browsers automatically block sending cookies on cross-site POST requests.
2
CSRF Tokens ('csrf-csrf'): Generate cryptographically signed anti-CSRF tokens that must be sent in custom HTTP headers on mutation requests (POST/PUT/DELETE).

Code Implementation Example

javascript
import express from 'express';
import { doubleCsrf } from 'csrf-csrf';

const app = express();

const { doubleCsrfProtection, generateToken } = doubleCsrf({
  getSecret: () => 'super-secret-key',
  cookieName: '__Host-psrf.x-csrf-token',
  cookieOptions: { sameSite: 'lax', secure: true, httpOnly: true }
});

app.get('/api/csrf-token', (req, res) => {
  const token = generateToken(req, res);
  res.json({ csrfToken: token });
});

// Protect state-changing endpoints with CSRF token verification middleware
app.post('/api/transfer', doubleCsrfProtection, (req, res) => {
  res.json({ status: 'Transfer complete' });
});
💡Defending state-changing endpoints against CSRF using doubleCsrf token verification.
🎯 Interview Key Takeaway

Set SameSite=Strict on cookies and enforce CSRF token validation on state-changing endpoints.

#CSRF#Security#Tokens#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?