0
0
NodejsDebug / FixBeginner · 4 min read

How to Prevent CSRF Attacks in Node.js Securely

To prevent CSRF attacks in Node.js, use middleware like csurf that generates and validates tokens for each user session. This ensures that requests come from trusted sources and not malicious sites.
🔍

Why This Happens

CSRF (Cross-Site Request Forgery) happens when a malicious website tricks a user's browser into sending unwanted requests to a trusted site where the user is logged in. This can cause actions like changing passwords or making purchases without the user's consent.

Without protection, your Node.js app accepts requests without verifying their origin, making it vulnerable.

javascript
import express from 'express';

const app = express();

app.use(express.json());

app.post('/change-password', (req, res) => {
  // No CSRF protection here
  const newPassword = req.body.password;
  // Imagine password change logic here
  res.send('Password changed');
});

app.listen(3000);
Output
Any POST request to /change-password will be accepted without verifying the request source, allowing CSRF attacks.
🔧

The Fix

Use the csurf middleware to add CSRF tokens to your forms and verify them on requests. This token is unique per user session and must be included in requests, blocking unauthorized requests from other sites.

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

const app = express();

app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));

// 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="/change-password" method="POST">
      <input type="hidden" name="_csrf" value="${req.csrfToken()}" />
      <input type="password" name="password" placeholder="New Password" />
      <button type="submit">Change Password</button>
    </form>
  `);
});

app.post('/change-password', csrfProtection, (req, res) => {
  const newPassword = req.body.password;
  // Password change logic here
  res.send('Password changed safely');
});

app.listen(3000);
Output
The server only accepts POST requests to /change-password that include a valid CSRF token, blocking forged requests.
🛡️

Prevention

Always use CSRF protection middleware like csurf in your Node.js apps that handle user sessions and sensitive actions. Use cookies or sessions to store tokens securely. Include tokens in all state-changing requests (POST, PUT, DELETE).

Keep dependencies updated and test your app with tools like OWASP ZAP to detect CSRF vulnerabilities.

⚠️

Related Errors

Other common security issues related to CSRF include:

  • Missing SameSite cookie attribute: Cookies without SameSite can be sent cross-site, increasing CSRF risk.
  • Session fixation: Attackers forcing a user to use a known session ID.
  • Cross-Site Scripting (XSS): Can be combined with CSRF to steal tokens.

Fixes include setting SameSite=Lax or Strict on cookies and sanitizing user input.

Key Takeaways

Use the csurf middleware to generate and verify CSRF tokens in Node.js apps.
Include CSRF tokens in all forms and state-changing requests to block forged requests.
Store tokens securely using cookies or sessions with proper attributes like SameSite.
Keep dependencies updated and test your app for CSRF vulnerabilities regularly.
Understand related security issues like SameSite cookies and XSS to strengthen protection.