JAVASCRIPT

Implementing CSRF Protection in Express.js with `csurf`

Secure your Express.js web forms and API endpoints against Cross-Site Request Forgery (CSRF) attacks using the `csurf` middleware and synchronizer tokens.

const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session'); // Required for csurf
const csurf = require('csurf');
const bodyParser = require('body-parser');

const app = express();

// 1. Configure session middleware
app.use(cookieParser());
app.use(session({
  secret: 'your_strong_secret_key_here_for_session',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'lax' }
}));

// 2. Add body-parser middleware before csurf for POST requests
// only needed if you are parsing application/x-www-form-urlencoded or application/json
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 3. Initialize csurf middleware
// This middleware reads the token from the request and verifies it.
app.use(csurf({ cookie: true })); // Use cookie-based token storage

// Helper to render a basic form (for demonstration)
app.set('view engine', 'ejs'); // Or any templating engine you use
app.set('views', __dirname + '/views');

// In a real app, create a 'views' directory with 'form.ejs'
/*
<!-- views/form.ejs -->
<!DOCTYPE html>
<html>
<head><title>CSRF Demo</title></head>
<body>
  <h1>Submit Secure Data</h1>
  <form action="/submit" method="POST">
    <input type="hidden" name="_csrf" value="<%= csrfToken %>">
    <label for="message">Message:</label>
    <input type="text" id="message" name="message" required>
    <button type="submit">Submit</button>
  </form>
</body>
</html>
*/

// GET route to render the form with the CSRF token
app.get('/', (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

// POST route to handle form submission (CSRF protected)
app.post('/submit', (req, res) => {
  // Access the CSRF token from req.body (or req.headers/req.query if configured differently)
  // csurf middleware already verified it, if it failed, this route wouldn't be reached.
  const { message } = req.body;
  console.log('Received message:', message);
  res.send(`Data submitted securely: ${message}`);
});

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Express.js snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using the `csurf` middleware. CSRF attacks trick users into executing unwanted actions on web applications where they are authenticated. The `csurf` middleware works by generating a unique token for each session, which is embedded in forms (typically as a hidden field) or sent via headers. On subsequent requests, the middleware verifies that the submitted token matches the one associated with the user's session. If they don't match, the request is rejected, preventing unauthorized actions. This setup requires `express-session` and `cookie-parser`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs