JAVASCRIPT
Implement CSRF Protection Middleware in Express.js
Secure your Express.js applications against Cross-Site Request Forgery (CSRF) attacks by implementing the `csurf` middleware for robust token validation on state-changing requests.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csrf = require('csurf');
const path = require('path');
const app = express();
// Configure session middleware first (required by csurf)
app.use(cookieParser());
app.use(session({
secret: 'super-secret-key-for-session', // Use a strong, unique secret
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true, // Prevent client-side JS from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Only send over HTTPS in production
maxAge: 3600000 // 1 hour
}
}));
// CSRF protection middleware
const csrfProtection = csrf({ cookie: true }); // Uses cookies for token storage
app.use(express.urlencoded({ extended: false })); // For parsing form submissions
app.use(express.json()); // For parsing JSON bodies
// Apply CSRF protection to routes that require it (e.g., POST, PUT, DELETE)
app.get('/', csrfProtection, (req, res) => {
// Render a form with the CSRF token
res.send(`
<h1>CSRF Protected Form</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 the token is valid, process the request
res.send(`Successfully processed: ${req.body.message}`);
});
// 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}`);
console.log('Visit http://localhost:3000');
});
How it works: This snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection in an Express.js application using the `csurf` middleware. CSRF attacks trick authenticated users into executing unwanted actions. The `csurf` middleware generates a unique, cryptographically secure token for each session (`req.csrfToken()`) and expects it to be present in subsequent non-GET requests (e.g., POST form submissions). If the token is missing or invalid, the request is rejected, thereby preventing unauthorized state-changing operations. Session and cookie middlewares are prerequisites for `csurf`.