Security javascript Intermediate

Express CSRF Protection with Double Submit

Implement double-submit CSRF protection in Express without server-side session storage.

javascript
const crypto = require("crypto");
const cookieParser = require("cookie-parser");

app.use(cookieParser());

app.use((req, res, next) => {
  if (!req.cookies.csrf_token) {
    res.cookie("csrf_token", crypto.randomBytes(32).toString("hex"), { sameSite: "strict" });
  }
  next();
});

function verifyCsrf(req, res, next) {
  const cookie = req.cookies.csrf_token;
  const header = req.headers["x-csrf-token"];
  if (!cookie || cookie !== header) return res.status(403).json({ error: "CSRF mismatch" });
  next();
}

app.post("/api/donate", verifyCsrf, (req, res) => res.json({ ok: true }));

Prerequisites

  • express >= 4
  • cookie-parser

Pro Tips

  • → Read the cookie in JS and send as X-CSRF-Token header on every mutation.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
javascript
Level
Intermediate
Read time
4 min
Published
Jun 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.