JAVASCRIPT
Implementing CSRF Protection in Node.js Express
Secure your Node.js Express applications against Cross-Site Request Forgery (CSRF) attacks by implementing robust token-based protection using the `csurf` middleware.
const express = require('express');
const cookieParser = require('cookie-parser');
const csurf = require('csurf');
const session = require('express-session');
const app = express();
const port = 3000;
// Use cookie-parser middleware
app.use(cookieParser());
// Configure session middleware (required for csurf to store token)
app.use(session({
secret: 'super-secret-key-for-session', // Replace with a strong, random key
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true }); // Token stored in a cookie
app.use(express.urlencoded({ extended: false })); // For parsing form data
// Example routes
app.get('/', csrfProtection, (req, res) => {
res.send(`
<h1>Welcome!</h1>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<label for="message">Message:</label>
<input type="text" id="message" name="message">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// If CSRF token is valid, process the form data
res.send(`Data received: ${req.body.message}`);
});
// Error handling for CSRF issues
app.use((err, req, res, next) => {
if (err.code !== 'EBADCSRFTOKEN') return next(err);
res.status(403).send('Invalid CSRF token.');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How it works: This snippet demonstrates implementing CSRF protection in an Express application using the `csurf` and `express-session` middlewares. A unique CSRF token is generated for each session and embedded as a hidden field in forms. On submission, the server verifies this token against the one stored in the session or cookie. This ensures that form submissions originate from the legitimate application, preventing malicious sites from tricking users into performing unwanted actions. The `cookie: { secure: true }` option is crucial for production environments to ensure tokens are only sent over HTTPS.