GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Vert.x

Cross-Site Scripting (XSS) in APIs occurs when untrusted input is reflected in the response without proper sanitization or incorrect Content-Type headers. In Vert.x, if you're building a REST API but accidentally serve data as 'text/html' or allow the browser to sniff the content type, you're opening the door for an attacker to execute malicious scripts in the context of your application's origin.

The Vulnerable Pattern

router.get("/api/user").handler(ctx -> {
  String username = ctx.request().getParam("username");
  // VULNERABLE: Direct reflection and incorrect content type
  ctx.response()
     .putHeader("Content-Type", "text/html")
     .end("{\"user\": \"" + username + "\"}");
});

The Secure Implementation

The fix targets two layers: Header Enforcement and Data Serialization. First, we set 'Content-Type' to 'application/json', which instructs the browser to treat the payload as data, not as a document to be rendered. Second, we add 'X-Content-Type-Options: nosniff' to prevent MIME-sniffing attacks where a browser might ignore the header and try to interpret the JSON as HTML. Finally, using Vert.x's 'JsonObject' ensures that the data is correctly encoded, preventing any broken JSON structures that could lead to secondary injection points.

router.get("/api/user").handler(ctx -> {
  String username = ctx.request().getParam("username");
  // SECURE: Use JsonObject for serialization and enforce strict headers
  JsonObject body = new JsonObject().put("user", username);
  ctx.response()
     .putHeader("Content-Type", "application/json")
     .putHeader("X-Content-Type-Options", "nosniff")
     .putHeader("Content-Security-Policy", "default-src 'none'")
     .end(body.encode());
});
System Alert • ID: 8206
Target: API Responses API
Potential Vulnerability

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.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.