JAVASCRIPT

Implement CSRF Protection with Tokens in Express.js

Protect your web application from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique, synchronized tokens for sensitive operations in Express.js.

const express = require('express');
const cookieParser = require('cookie-parser');
const csurf = require('csurf');
const bodyParser = require('body-parser');

const app = express();

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(csurf({ cookie: true })); // Use cookie-based CSRF tokens

// Middleware to make CSRF token available to templates (e.g., Pug, EJS)
app.use((req, res, next) => {
  res.locals.csrfToken = req.csrfToken();
  next();
});

app.get('/', (req, res) => {
  // In a real app, you'd render an HTML form with a hidden input for csrfToken
  res.send(`
        <form action="/process" method="POST">
          <input type="hidden" name="_csrf" value="${req.csrfToken()}">
          <input type="text" name="message" placeholder="Your message">
          <button type="submit">Submit</button>
        </form>
        <p>CSRF Token (for debugging): ${req.csrfToken()}</p>
      `);
});

app.post('/process', (req, res) => {
  // CSRF token is automatically validated by csurf middleware before reaching here
  res.send(`Data received: ${req.body.message}. CSRF token validated.`);
});

app.use((err, req, res, next) => {
  if (err.code !== 'EBADCSRFTOKEN') return next(err);
  res.status(403).send('Invalid CSRF Token. Request blocked.');
});

app.listen(3000, () => console.log('App running on http://localhost:3000'));
How it works: This snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection in an Express.js application using the `csurf` middleware. `csurf` generates a unique token for each session and expects this token to be present in the request body, header, or query string for non-GET requests. By including the token in a hidden form field, the middleware automatically validates it, preventing malicious requests from third-party sites from manipulating user sessions. The error handling gracefully manages invalid token submissions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs