How to Prevent XSS Attacks in Express Applications
XSS in Express, always sanitize user input and use security middleware like helmet. Avoid rendering raw user data directly in responses without escaping or sanitizing it.Why This Happens
XSS happens when an attacker injects malicious scripts into web pages viewed by other users. In Express, this often occurs if you include user input directly in HTML responses without cleaning it. The browser then runs the harmful script, which can steal data or hijack user sessions.
import express from 'express'; const app = express(); app.get('/greet', (req, res) => { const name = req.query.name || 'Guest'; res.send(`<h1>Hello, ${name}!</h1>`); // Unsafe: directly inserts user input }); app.listen(3000);
The Fix
Fix this by sanitizing or escaping user input before including it in HTML. Use libraries like dompurify or sanitize-html to clean input. Also, use helmet middleware to set security headers that help prevent XSS.
import express from 'express'; import helmet from 'helmet'; import sanitizeHtml from 'sanitize-html'; const app = express(); app.use(helmet()); app.get('/greet', (req, res) => { const rawName = req.query.name || 'Guest'; const safeName = sanitizeHtml(rawName, { allowedTags: [], allowedAttributes: {} }); res.send(`<h1>Hello, ${safeName}!</h1>`); // Safe: input sanitized }); app.listen(3000);
Prevention
Always validate and sanitize all user inputs on the server side before using them in responses. Use security middleware like helmet to add HTTP headers that protect against XSS. Avoid using innerHTML or similar methods on the client without sanitizing. Regularly update dependencies and audit your code for unsafe data handling.
- Use
helmet()middleware in Express. - Sanitize inputs with libraries like
sanitize-htmlordompurify. - Escape output when rendering templates.
- Use Content Security Policy (CSP) headers to restrict script sources.
Related Errors
Other common security issues related to XSS include:
- CSRF (Cross-Site Request Forgery): Use CSRF tokens to prevent unauthorized actions.
- SQL Injection: Use parameterized queries to avoid injection attacks.
- Open Redirects: Validate URLs before redirecting users.