JAVASCRIPT
Implement CSRF Protection in Node.js Express Application
Protect your web application from Cross-Site Request Forgery (CSRF) attacks by integrating CSRF tokens into your Node.js Express server 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(bodyParser.urlencoded({ extended: false }));
// Configure session middleware
app.use(session({
secret: 'your_strong_secret_key', // Replace with a strong, random key
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'lax' }
}));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
// Route to display a form with 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="data">
<button type="submit">Submit</button>
</form>
`);
});
// Route to process form submission with CSRF protection
app.post('/process', bodyParser.json(), csrfProtection, (req, res) => {
// Access req.body.data after CSRF validation
res.send('Data processed successfully with CSRF protection!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How it works: This snippet demonstrates how to implement CSRF (Cross-Site Request Forgery) protection in an Express.js application using the `csurf` middleware. It sets up a session, then uses `csurf` to generate a unique token for each request. This token is embedded in forms as a hidden field. On submission, the middleware verifies that the token sent with the request matches the one stored in the session/cookie, preventing unauthorized requests from external sites.