← Back to all snippets
JAVASCRIPT

Implement CSRF Protection with Anti-Forgery Tokens (Node.js)

Protect your Node.js Express web application from Cross-Site Request Forgery (CSRF) attacks by integrating and validating anti-forgery tokens.

const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csurf = require('csurf');
const bodyParser = require('express-body-parser'); // Typically used for POST data

const app = express();

// 1. Setup session middleware
app.use(cookieParser());
app.use(session({
  secret: 'aVeryStrongSecretKey123', // Use a strong, unique secret in production
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));

// 2. Setup csurf middleware (after session, before body-parser for POSTs)
app.use(bodyParser.urlencoded({ extended: false })); // for parsing application/x-www-form-urlencoded
app.use(bodyParser.json()); // for parsing application/json
app.use(csurf({ cookie: true })); // Stores CSRF token in a cookie

// 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);
  }
});

// 3. Example route to get a CSRF token (for initial page load/form)
app.get('/form', (req, res) => {
  res.send(`
        <form action="/process" method="POST">
          <input type="hidden" name="_csrf" value="${req.csrfToken()}">
          <input type="text" name="data" placeholder="Enter data">
          <button type="submit">Submit</button>
        </form>
      `);
});

// 4. Example route to process data (requires valid CSRF token)
app.post('/process', (req, res) => {
  // If we reach here, CSRF token was valid
  res.send(`Data processed: ${req.body.data}`);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection in an Express.js application using the `csurf` middleware. It relies on a session to store and verify a unique CSRF token for each user. When a form is rendered, a hidden input field containing this token is added. On subsequent POST requests, `csurf` verifies that the submitted token matches the one stored in the session, effectively preventing malicious third-party sites from tricking authenticated users into performing unintended actions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs