JAVASCRIPT

Implement CSRF Protection in Express.js Applications

Protect your web applications from Cross-Site Request Forgery (CSRF) attacks by integrating the 'csurf' middleware in your Express.js server, ensuring form submissions are legitimate.

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(bodyParser.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded
app.use(cookieParser());
app.use(session({
  secret: 'super_secret_key_for_session',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));

// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });

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

app.post('/process', bodyParser.json(), csrfProtection, (req, res) => {
  if (req.body._csrf !== req.csrfToken()) {
    return res.status(403).send('CSRF token mismatch!');
  }
  res.send(`Item received: ${req.body.item || 'No item'}. CSRF token valid!`);
});

// Error handler for CSRF issues
app.use((err, req, res, next) => {
  if (err.code !== 'EBADCSRFTOKEN') return next(err);
  res.status(403).send('Invalid CSRF token - This request was potentially forged.');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${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 authenticated users into submitting unintended requests. The 'csurf' middleware generates a unique, secret token for each user, stores it in their session, and embeds it in a hidden form field. On submission, the server verifies if the token from the form matches the one in the session. If they don't match, the request is rejected, preventing unauthorized actions. This setup requires `cookie-parser` and `express-session` middleware to function correctly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs