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.
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.
Similar Modules
TOTP Two-Factor Auth
Generate and verify time-based one-time passwords (TOTP) compatible with Google Authenticator.
python
·
Advanced
ClamAV Malware Scanner Cron
Run ClamAV on upload directory and quarantine infected files automatically.
bash
·
Advanced
Rate Limiter Decorator for CLI Tools
Decorator that throttles function calls to N per second — useful for API clients.
python
·
Intermediate