Fix XSS in API Responses in ElysiaJS
XSS in ElysiaJS APIs typically manifests when raw strings containing unsanitized user input are returned, leading browsers to interpret the response as HTML. Even in an API context, if an attacker can force a victim's browser to render the response (e.g., via a direct link or iframe), they can execute arbitrary JavaScript in the context of the application's origin.
The Vulnerable Pattern
import { Elysia } from 'elysia';
const app = new Elysia() .get(‘/v1/status/:message’, ({ params }) => { // VULNERABLE: Implicitly returns text/plain or text/html. // An attacker can pass ) returnStatus: ${params.message}; }) .listen(3000);
The Secure Implementation
The vulnerability stems from the 'Reflected XSS' pattern where input is mirrored back without encoding. To harden the ElysiaJS handler: 1. Use 'isomorphic-dompurify' to strip malicious payloads from strings. 2. Avoid returning raw strings; by returning an Object, Elysia automatically sets the 'Content-Type' to 'application/json', which browsers will not execute as HTML. 3. Implement 'X-Content-Type-Options: nosniff' to prevent MIME-type sniffing and a strict CSP to disable script execution entirely in the API response context.
import { Elysia, t } from 'elysia'; import DOMPurify from 'isomorphic-dompurify';const app = new Elysia() .get(‘/v1/status/:message’, ({ params, set }) => { // SECURE: 1. Sanitize the input const safeMessage = DOMPurify.sanitize(params.message);
// SECURE: 2. Force JSON response to prevent HTML rendering // SECURE: 3. Set strict security headers set.headers['Content-Security-Policy'] = "default-src 'none'; frame-ancestors 'none';"; set.headers['X-Content-Type-Options'] = 'nosniff'; return { status: 'ok', message: safeMessage };
}, { params: t.Object({ message: t.String() }) }) .listen(3000);
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.