Fix XSS in API Responses in LoopBack
Reflected XSS in API endpoints isn't just a frontend problem; it's a failure of the backend to enforce strict data boundaries. In LoopBack, if you manually override response headers to serve HTML or fail to sanitize 'any' type model properties reflected in the response, you're opening a vector for script execution. An attacker can inject a payload that executes in the context of the victim's session when the browser misinterprets the API response.
The Vulnerable Pattern
@get('/profile/raw')
async getRawProfile(@param.query.string('username') username: string): Promise {
// VULNERABILITY: Manually setting text/html and reflecting unsanitized input
this.response.set('Content-Type', 'text/html');
return `Profile for: ${username}
`;
}
The Secure Implementation
To kill XSS in LoopBack, follow three rules: 1. Never manually set 'Content-Type' to 'text/html' for data-driven responses; stick to 'application/json'. 2. Use the '@response' decorator to strictly define output schemas, ensuring the framework handles serialization and header enforcement. 3. Ensure 'X-Content-Type-Options: nosniff' is enabled in your middleware (usually via Helmet) to prevent browsers from MIME-sniffing a JSON response into an executable HTML context. If you must return HTML, use a dedicated templating engine with auto-escaping or a library like DOMPurify on the input.
@get('/profile/secure')
@response(200, {
content: {
'application/json': {
schema: {type: 'object', properties: {username: {type: 'string'}}}
}
}
})
async getSecureProfile(@param.query.string('username') username: string): Promise
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.