JAVASCRIPT

Implementing CSRF Protection in a Node.js/Express Application

Secure your Node.js Express application against Cross-Site Request Forgery (CSRF) attacks by implementing a token-based protection mechanism 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();

// Middleware setup
app.use(cookieParser());
app.use(session({
  secret: 'super-secret-session-key', // Change this to a strong, random key in production
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production' }, // Use secure cookies in production
}));

// csurf middleware
// Requires cookie-parser and express-session to be set up first
const csrfProtection = csurf({ cookie: true });

// Body parser for POST requests
app.use(bodyParser.urlencoded({ extended: false }));

// Route for displaying a form with a CSRF token
app.get('/form', csrfProtection, (req, res) => {
  res.send(`
    <h1>Submit Data</h1>
    <form action="/process" method="POST">
      <input type="text" name="item" placeholder="Enter item">
      <input type="hidden" name="_csrf" value="${req.csrfToken()}">
      <button type="submit">Submit</button>
    </form>
  `);
});

// Route for processing the form submission
app.post('/process', csrfProtection, (req, res) => {
  console.log('Received item:', req.body.item);
  res.send('Data processed successfully!');
});

// Error handling 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}`);
});
How it works: This Node.js Express snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using the 'csurf' middleware. CSRF attacks trick users into executing unwanted actions on a web application where they are currently authenticated. The 'csurf' middleware generates a unique, secret token per user session. This token is embedded in forms as a hidden field and verified on subsequent POST requests. If the token doesn't match, the request is blocked, protecting state-changing actions from malicious external requests. Remember to configure session and cookie-parser middleware before csurf.

Need help integrating this into your project?

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

Hire DigitalCodeLabs