GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Spiral

Spiral's high-performance architecture doesn't protect you from fundamental injection flaws. XSS in API responses occurs when an attacker-controlled payload is reflected back into the DOM via an improperly secured endpoint. In Spiral, this usually happens when developers manually construct responses or mismanage the 'Content-Type' header, leading the browser to execute malicious scripts instead of parsing data.

The Vulnerable Pattern

public function index(ServerRequestInterface $request): ResponseInterface
{
    $name = $request->getQueryParams()['name'] ?? 'Guest';
    $response = new \Spiral\Http\Response();
    // VULNERABLE: Reflecting raw input directly into a text/html response
    $response->getBody()->write("

Welcome, $name

"); return $response->withHeader('Content-Type', 'text/html'); }

The Secure Implementation

To mitigate XSS in Spiral, you must enforce strict output handling. 1. Use the 'ResponseWrapper' service to return JSON payloads; this forces the browser to treat the body as data, not markup. 2. If you must return HTML, use Spiral's 'Views' (Stempler), which provides automatic contextual escaping. 3. Avoid manual manipulation of 'Psr\Http\Message\StreamInterface' with raw user input. 4. Implement a 'Content-Security-Policy' (CSP) middleware to block inline script execution as a secondary layer of defense.

public function index(ResponseWrapper $response, ServerRequestInterface $request): ResponseInterface
{
    $name = $request->getQueryParams()['name'] ?? 'Guest';
    // SECURE: Utilize ResponseWrapper to return JSON.
    // This automatically sets 'Content-Type: application/json' and escapes characters.
    return $response->json([
        'message' => 'Welcome',
        'user' => $name
    ], 200);
}
System Alert • ID: 7255
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.