JAVASCRIPT

Implementing CSRF Protection in Node.js with Express and csurf

Secure your Node.js web applications against Cross-Site Request Forgery (CSRF) attacks by integrating `csurf` middleware for token-based protection in forms.

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(express.urlencoded({ extended: false }));
app.use(session({
    secret: 'superSecretKey',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: process.env.NODE_ENV === 'production' }
}));

const csrfProtection = csurf({ cookie: true });

// Render 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()}">
            <label for="item">Item:</label>
            <input type="text" id="item" name="item">
            <button type="submit">Submit</button>
        </form>
    `);
});

// Process form submission with CSRF token validation
app.post('/process', csrfProtection, (req, res) => {
    console.log('Processed item:', req.body.item);
    res.send('Success!');
});

// Error handling for CSRF
app.use((err, req, res, next) => {
    if (err.code !== 'EBADCSRFTOKEN') return next(err);
    res.status(403).send('CSRF token invalid or missing.');
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
How it works: This Node.js snippet demonstrates how to protect an Express application from Cross-Site Request Forgery (CSRF) attacks using the `csurf` middleware. CSRF attacks trick authenticated users into executing unwanted actions on a web application. The `csurf` middleware generates a unique, secret token for each user, embeds it in forms, and validates it upon submission. If the token is missing or invalid, the request is rejected, preventing malicious requests from unauthorized sources. This ensures that state-changing requests originate from legitimate users through your application's interface.

Need help integrating this into your project?

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

Hire DigitalCodeLabs