0
0
ExpressDebug / FixBeginner · 4 min read

How to Prevent XSS Attacks in Express Applications

To prevent 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.

javascript
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);
Output
<h1>Hello, <script>alert('XSS')</script>!</h1> // This runs the script in the browser
🔧

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.

javascript
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);
Output
<h1>Hello, &lt;script&gt;alert('XSS')&lt;/script&gt;!</h1> // Script tags are escaped and not executed
🛡️

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-html or dompurify.
  • 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.

Key Takeaways

Always sanitize and escape user input before including it in HTML responses.
Use Express middleware like helmet to add security headers that help prevent XSS.
Avoid rendering raw user data directly without cleaning it first.
Implement Content Security Policy headers to restrict allowed scripts.
Regularly update dependencies and audit your code for security risks.