Fix XSS in API Responses in Javalin
Reflected XSS in Javalin APIs occurs when untrusted input is echoed back to the client without proper output encoding or restrictive Content-Type headers. While APIs typically serve JSON, developers often mistakenly use 'ctx.html()' or 'ctx.result()' with user-controlled data, allowing attackers to inject script tags that execute in the context of the victim's session.
The Vulnerable Pattern
app.get("/greet/{name}", ctx -> {
String name = ctx.pathParam("name");
// VULNERABLE: Directly embedding user input into an HTML response context
ctx.html("Welcome, " + name + "
");
});
The Secure Implementation
To kill XSS in Javalin, stop using ctx.html() for dynamic data. The browser triggers XSS when it sees 'text/html'. By using ctx.json(), Javalin sets 'Content-Type: application/json', which modern browsers will not parse as executable HTML. If you must return HTML, run the input through a robust sanitizer like the OWASP Java HTML Sanitizer before rendering. Additionally, implement a strict Content-Security-Policy (CSP) header to block inline scripts.
app.get("/greet/{name}", ctx -> { String name = ctx.pathParam("name"); // SECURE: Use ctx.json() to enforce application/json Content-Type // This prevents the browser from interpreting the response as HTML/JS ctx.json(Map.of("message", "Welcome, " + name)); });
// Alternative: Manual Content-Type enforcement for plain text app.get(“/text/{name}”, ctx -> { ctx.contentType(“text/plain”).result(ctx.pathParam(“name”)); });
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.