Fix XSS in API Responses in Laravel
Think APIs are immune to XSS? Think again. If your Laravel backend reflects user input in JSON responses without strict Content-Type enforcement or proper encoding, you're handing an XSS vector to anyone with Burp Suite. The risk manifests when browsers 'sniff' the response as HTML or when a frontend SPA blindly renders your API data using unsafe methods like v-html or dangerouslySetInnerHTML.
The Vulnerable Pattern
public function search(Request $request) {
$query = $request->input('q');
// VULNERABLE: Manual response construction or returning raw strings
// can lead to 'text/html' sniffing or injection if interpreted by the client.
return response('{"results": "' . $query . '"}', 200)->header('Content-Type', 'text/html');
}
The Secure Implementation
To kill XSS in Laravel APIs, stop building JSON strings manually. Use `response()->json()`, which internally uses `json_encode()`, effectively escaping HTML entities. Crucially, set the `X-Content-Type-Options: nosniff` header to prevent browsers from ignoring the `application/json` mime-type and executing the payload as HTML. Finally, ensure your frontend devs aren't using 'raw' rendering directives; the backend is your first line of defense, but the browser is the execution environment.
public function search(Request $request) {
// SECURE: Use Laravel's response factory to force application/json
// and automatic JSON encoding which handles character escaping.
return response()->json([
'results' => $request->input('q')
], 200, [
'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'"
]);
}
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.