JAVASCRIPT
Implement CSRF Protection with Node.js Express
Secure your Node.js Express application 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 session = require('express-session');
const csurf = require('csurf');
const bodyParser = require('body-parser');
const app = express();
app.use(cookieParser());
app.use(session({
secret: 'super-secret-key-for-session', // Use a strong, unique secret
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'Lax' }
}));
app.use(bodyParser.urlencoded({ extended: false }));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
// Route to render a form with a CSRF token
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="message" placeholder="Your message">
<button type="submit">Submit</button>
</form>
`);
});
// Route to process the form submission
app.post('/process', csrfProtection, (req, res) => {
// Access req.body here after CSRF check
res.send(`Message 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('CSRF token invalid or missing');
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
How it works: This snippet demonstrates how to protect an Express application from CSRF attacks using the `csurf` middleware. It sets up session and cookie parsers, then applies `csurf` to routes requiring protection. A hidden input field in the form holds the generated CSRF token, which is then validated upon form submission. Any requests without a valid token are rejected, preventing unauthorized actions.