JAVASCRIPT
Implementing CSRF Protection in Express.js
Implement robust Cross-Site Request Forgery (CSRF) protection in your Node.js Express application using a secure token-based approach.
// Install: npm install express express-session csurf
const express = require('express');
const session = require('express-session');
const csurf = require('csurf');
const bodyParser = require('body-parser');
const app = express();
// Use session middleware (required by csurf)
app.use(session({
secret: 'your_super_secret_key_here', // Replace with a strong, random string
resave: false,
saveUninitialized: true,
cookie: { secure: true, httpOnly: true, sameSite: 'Lax' } // Secure and HttpOnly are critical for production
}));
// Use body-parser for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
// Apply CSRF protection to POST routes
app.get('/form', csrfProtection, (req, res) => {
res.send(`
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<input type="text" name="data" placeholder="Enter data">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// If we got this far, the CSRF token was valid
res.send(`Data received: ${req.body.data}`);
});
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('Invalid CSRF token');
} else {
next(err);
}
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
How it works: This Node.js Express snippet demonstrates how to implement CSRF (Cross-Site Request Forgery) protection using the `csurf` middleware. It requires `express-session` to manage session state. A unique CSRF token is generated for each request and embedded as a hidden field in forms. On submission, the `csurf` middleware validates this token, ensuring that the request originated from a legitimate source and preventing attackers from forging requests on behalf of authenticated users.