JAVASCRIPT
Implementing CSRF Protection with csurf Middleware in Node.js
Protect your Node.js Express application from Cross-Site Request Forgery (CSRF) attacks using the `csurf` middleware for token-based validation.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csurf = require('csurf');
const app = express();
app.use(cookieParser());
app.use(session({ secret: 'your-secret-key', cookie: { secure: true, httpOnly: true }, resave: false, saveUninitialized: true }));
app.use(csurf({ cookie: true }));
app.get('/', (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', express.urlencoded({ extended: false }), (req, res) => {
// If CSRF token is invalid, csurf middleware will throw an error
// Access req.body.data after successful CSRF validation
res.send('Data processed successfully!');
});
// Error handling middleware for CSRF
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('Invalid CSRF token.');
} else {
next(err);
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This snippet demonstrates CSRF protection in an Express.js application using the `csurf` middleware. It sets up session and cookie parsers, then `csurf` generates a unique token for each session. This token is embedded in forms (e.g., as a hidden input `_csrf`). On form submission, `csurf` verifies that the token sent with the request matches the one stored in the session/cookie, preventing unauthorized requests originating from other sites. An error handler catches invalid tokens.