Fix XSS in API Responses in Go Fiber
APIs aren't magically immune to XSS. If your Go Fiber backend reflects unsanitized user input and the browser interprets the response as HTML (either via 'text/html' or MIME-sniffing), you've got a Reflected XSS vulnerability. Don't rely on the client-side framework to do your job; secure the transport layer and sanitize the output.
The Vulnerable Pattern
app.Get("/user", func(c *fiber.Ctx) error {
name := c.Query("name")
// VULNERABLE: Direct reflection of input without encoding or correct Content-Type
c.Set("Content-Type", "text/html")
return c.SendString("Welcome, " + name + "
")
})
The Secure Implementation
The exploit occurs because Fiber's SendString method writes raw bytes to the response body. If an attacker passes as a query parameter, the browser executes it. To remediate: 1. Default to c.JSON()—it forces the application/json MIME type, preventing browsers from rendering the payload as HTML. 2. Use 'bluemonday' for input sanitization to strip malicious tags. 3. Explicitly set the 'X-Content-Type-Options: nosniff' header to kill MIME-type sniffing, ensuring the browser respects your declared Content-Type.
import "github.com/microcosm-cc/bluemonday" import "html"app.Get(“/user”, func(c *fiber.Ctx) error { name := c.Query(“name”)
// OPTION 1: Use c.JSON() which sets 'application/json' and escapes HTML characters // return c.JSON(fiber.Map{"message": "Welcome", "user": name}) // OPTION 2: Sanitize and Encode if HTML output is strictly required p := bluemonday.UGCPolicy() sanitized := p.Sanitize(name) encoded := html.EscapeString(sanitized) c.Set("X-Content-Type-Options", "nosniff") c.Set("Content-Type", "text/plain; charset=utf-8") return c.SendString("Welcome, " + encoded)
})
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.