JAVASCRIPT
Implementing CSRF Protection in Node.js Express Applications
Protect your Node.js Express application from Cross-Site Request Forgery (CSRF) attacks using the csurf middleware to generate and validate CSRF tokens.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csurf = require('csurf');
const app = express();
// Basic setup for session and cookie-parser
app.use(cookieParser());
app.use(session({
secret: 'your_super_secret_key',
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'lax' }
}));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
// Middleware to parse incoming request bodies
app.use(express.urlencoded({ extended: false })); // For form submissions
app.use(express.json()); // For JSON payloads
// Example route requiring CSRF protection for POST requests
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">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// If we reach here, CSRF token is valid
res.send(`Data received: ${req.body.data} (CSRF protected!)`);
});
// Error handler for CSRF issues
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('Invalid CSRF token.');
} else {
next(err);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
How it works: Cross-Site Request Forgery (CSRF) attacks trick authenticated users into executing unwanted actions. This snippet demonstrates how to implement CSRF protection in an Express.js application using the `csurf` middleware. It generates a unique, secret token for each user session, embeds it in forms (as a hidden field), and verifies it on subsequent requests. If the token is missing or invalid, the request is rejected, preventing attackers from forging requests.