How to Prevent CSRF Attacks in Node.js Securely
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.
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);
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.
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);
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
SameSitecan 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.