Fix XSS in API Responses in Lumen
XSS in APIs occurs when unsanitized user input is reflected in the response body, coupled with a loose Content-Type (like text/html). In Lumen, returning raw strings or failing to enforce JSON headers allows browsers to sniff and execute malicious payloads. Kill the bug by enforcing strict JSON responses and proper encoding.
The Vulnerable Pattern
$router->get('/greet/{name}', function ($name) {
// VULNERABLE: Returns raw string, default content-type may be text/html
// Payload: /greet/
return response("Hello, " . $name);
});
The Secure Implementation
To prevent XSS in Lumen, you must ensure the browser never interprets the API response as HTML. Use the response()->json() method; this forces the 'Content-Type: application/json' header and uses json_encode(), which prevents the browser from executing script tags. Always pair this with a global middleware that sets 'X-Content-Type-Options: nosniff' to stop browsers from MIME-sniffing a JSON response into an HTML context.
$router->get('/greet/{name}', function ($name) { // SECURE: Use the json() helper to force application/json and auto-escape return response()->json([ 'message' => 'Hello, ' . $name ], 200); });
// Alternative: Explicitly set headers and use htmlspecialchars if returning text // return response(htmlspecialchars($name))->header(‘Content-Type’, ‘text/plain’);
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.