JAVASCRIPT

Implementing Cross-Site Request Forgery (CSRF) Protection

Protect your Node.js Express application from CSRF attacks using the `csurf` middleware to generate and validate CSRF tokens for state-changing requests.

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

const app = express();

app.use(express.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded
app.use(cookieParser());

// Configure session middleware (required for csurf to store token)
app.use(session({
  secret: 'your-very-strong-secret-key-here-for-sessions',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));

// CSRF middleware
app.use(csurf({ cookie: true })); // Use cookie for storing CSRF token

// Error handler for CSRF issues
app.use((err, req, res, next) => {
  if (err.code !== 'EBADCSRFTOKEN') return next(err);
  res.status(403).json({ message: 'Invalid CSRF token.' });
});

// Route to get CSRF token (e.g., for frontend to include in forms)
app.get('/api/csrf-token', (req, res) => {
  res.json({ csrfToken: req.csrfToken() });
});

// Example protected route for POST requests
app.post('/api/submit-data', (req, res) => {
  // req.body._csrf is automatically checked by csurf for POST requests
  res.json({ message: 'Data submitted securely with CSRF protection!' });
});

const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement CSRF protection in an Express.js application using the `csurf` middleware. CSRF attacks trick users into performing unwanted actions on a web application where they are currently authenticated. The `csurf` middleware generates a unique token for each session, which must be included in all state-changing requests (like POST, PUT, DELETE). The server then verifies this token, ensuring that the request originated from a legitimate source and not from a malicious third party.

Need help integrating this into your project?

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

Hire DigitalCodeLabs