0
0
ExpressDebug / FixBeginner · 4 min read

How to Prevent CSRF Attacks in Express: Simple Steps

To prevent CSRF attacks in Express, use the csurf middleware which adds a secret token to forms and verifies it on requests. This token ensures requests come from your site, blocking malicious cross-site requests.
🔍

Why This Happens

CSRF (Cross-Site Request Forgery) happens when a malicious site tricks a user's browser into sending unwanted requests to your Express app. Without protection, your app can't tell if a request is from your site or an attacker.

Here is an example of an Express app without CSRF protection:

javascript
import express from 'express';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/transfer', (req, res) => {
  // Imagine this transfers money without verifying the request origin
  res.send('Transfer completed');
});

app.listen(3000);
Output
No error, but the app is vulnerable to CSRF attacks.
🔧

The Fix

Use the csurf middleware to add a CSRF token to your forms and verify it on POST requests. This token must be included in requests, so attackers cannot forge them.

Here is the fixed code with CSRF protection:

javascript
import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import csurf from 'csurf';

const app = express();
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

// Setup csurf middleware with cookie storage
const csrfProtection = csurf({ cookie: true });

app.get('/form', csrfProtection, (req, res) => {
  // Send form with CSRF token included
  res.send(`<form action='/transfer' method='POST'>
    <input type='hidden' name='_csrf' value='${req.csrfToken()}' />
    <button type='submit'>Transfer</button>
  </form>`);
});

app.post('/transfer', csrfProtection, (req, res) => {
  res.send('Transfer completed safely');
});

app.listen(3000);
Output
The form includes a CSRF token, and POST requests without the token are blocked.
🛡️

Prevention

Always use CSRF protection middleware like csurf in Express apps that handle state-changing requests (POST, PUT, DELETE). Include the CSRF token in all forms and AJAX requests.

  • Use cookie-parser or session middleware to store tokens.
  • Send the token as a hidden form field or in request headers.
  • Test your app by submitting forms without tokens to confirm protection.
  • Keep dependencies updated to get security fixes.
⚠️

Related Errors

Common related errors include:

  • ForbiddenError: invalid csrf token - Happens when the token is missing or incorrect.
  • Missing cookie-parser - CSRF middleware needs cookie or session parsing to work.
  • Token mismatch on AJAX requests - Ensure the token is sent in headers or request body.

Key Takeaways

Use the csurf middleware to add and verify CSRF tokens in Express.
Include the CSRF token in all forms and AJAX requests to prevent forgery.
Use cookie-parser or session middleware to store CSRF tokens securely.
Test your app by submitting requests without tokens to ensure protection.
Keep your dependencies updated to maintain security.