← Back to all snippets
JAVASCRIPT

Implement CSRF Protection in Express.js

Secure your Express.js applications against Cross-Site Request Forgery (CSRF) attacks by generating and validating CSRF tokens with the 'csurf' middleware.

// Install: npm install express csurf cookie-parser body-parser
const express = require('express');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

// Middleware setup
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(csrf({ cookie: true })); // Use cookie for storing csrf secret

// Example routes
app.get('/', (req, res) => {
  res.send(`
    <html>
    <head><title>CSRF Demo</title></head>
    <body>
      <h1>Submit Data</h1>
      <form action="/process" method="POST">
        <input type="text" name="data" placeholder="Enter something">
        <input type="hidden" name="_csrf" value="${req.csrfToken()}">
        <button type="submit">Submit</button>
      </form>
    </body>
    </html>
  `);
});

app.post('/process', (req, res) => {
  console.log('Received data:', req.body.data);
  res.send(`Data received: ${req.body.data}. CSRF token validated.`);
});

// 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.');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
How it works: This snippet demonstrates how to protect an Express.js application from Cross-Site Request Forgery (CSRF) attacks using the 'csurf' middleware. CSRF works by ensuring that all state-changing requests come from your application and not from a malicious third-party site. The 'csurf' middleware generates a unique, cryptographically secure token for each user, embeds it in forms (as a hidden input field), and then validates it upon form submission. If the token is missing or invalid, the request is rejected, preventing unauthorized actions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs