← Back to all snippets
JAVASCRIPT

Implementing CSRF Protection with Express

Protect your Node.js Express application from Cross-Site Request Forgery (CSRF) attacks by integrating a robust CSRF token generation and validation middleware like `csurf`.

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();

// Middleware setup
app.use(cookieParser());
app.use(session({
    secret: 'a_very_secret_key', // Replace with a strong, unique secret
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true, httpOnly: true, sameSite: 'lax' } // For production, set secure: true
}));
app.use(bodyParser.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded
app.use(csurf({ cookie: true })); // Use cookie for storing token, { cookie: { key: '_csrf', sameSite: 'lax' }} for more control

// Example route that requires CSRF protection
app.get('/form', (req, res) => {
    // Render a form with the CSRF token
    res.send(`
        <form action="/process" method="POST">
            <input type="hidden" name="_csrf" value="${req.csrfToken()}">
            <input type="text" name="item" placeholder="Enter item">
            <button type="submit">Submit</button>
        </form>
    `);
});

app.post('/process', (req, res) => {
    // If CSRF token is invalid, csurf middleware will throw an error
    res.send(`Item processed: ${req.body.item}. CSRF token verified.`);
});

// Error handler for CSRF issues
app.use((err, req, res, next) => {
    if (err.code !== 'EBADCSRFTOKEN') return next(err);
    res.status(403).send('CSRF token validation failed.');
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
How it works: Cross-Site Request Forgery (CSRF) attacks trick users into executing unwanted actions on web applications where they are authenticated. This snippet demonstrates implementing CSRF protection in an Express.js application using the `csurf` middleware. It generates a unique, secret token for each user session and embeds it in forms. When a form is submitted, the middleware verifies that the token sent with the request matches the expected token, effectively blocking malicious requests originating from other sites.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs