Fix XSS in API Responses in Express
API-based XSS is a common oversight. If your Express backend reflects user-controlled data without strict 'Content-Type' enforcement or proper encoding, browsers might sniff the response as HTML, executing malicious payloads. Don't trust that 'it's just an API'.
The Vulnerable Pattern
app.get('/api/profile', (req, res) => {
const { username } = req.query;
// VULNERABLE: res.send() can be interpreted as text/html by browsers.
// If username is , the browser may execute it.
res.send('{"username": "' + username + '"}');
});
The Secure Implementation
To kill XSS in Express APIs, you must control the browser's interpretation of the payload. 1. Use res.json() instead of res.send() to guarantee an 'application/json' Content-Type. 2. Implement 'helmet' middleware to set the 'X-Content-Type-Options: nosniff' header, which prevents browsers from MIME-sniffing the response into 'text/html'. 3. Sanitize and validate all incoming data using a library like 'express-validator' to ensure inputs conform to expected formats before they are processed.
const helmet = require('helmet'); const express = require('express'); const app = express();// Use Helmet to set X-Content-Type-Options: nosniff app.use(helmet());
app.get(‘/api/profile’, (req, res) => { const { username } = req.query;
// SECURE: res.json() forces application/json and properly serializes data. // Combined with ‘nosniff’, browsers won’t execute the payload as HTML. res.json({ username: username }); });
Your API Responses API
might be exposed to XSS
74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.