← Back to all snippets
JAVASCRIPT

Implement CSRF Protection in Web Applications

Safeguard your web forms and state-changing requests against Cross-Site Request Forgery (CSRF) attacks using token-based protection in Node.js/Express.

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

const app = express();

// Middleware setup
app.use(cookieParser());
app.use(session({
  secret: 'your_secret_key_here',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));

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

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

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

// Example route to process form submission
app.post('/process', csrfProtection, (req, res) => {
  console.log('Received data:', req.body.data);
  res.send('Data processed successfully!');
});

// Error handling 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 has been blocked.');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
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 executing unwanted actions. The `csurf` middleware generates a unique, cryptographically secure token for each session. This token is embedded in forms as a hidden field and must be submitted with any state-changing request (like POST, PUT, DELETE). The middleware then verifies that the submitted token matches the one stored in the session/cookie, blocking requests with invalid or missing tokens.

Need help integrating this into your project?

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

Hire DigitalCodeLabs