Fix XSS in API Responses in Chi
Reflected XSS in Chi-based APIs typically surfaces when untrusted URL parameters or body fields are echoed back in the response without an explicit 'Content-Type: application/json' header. If the browser sniffs the response as HTML, it will execute injected scripts. As a Senior AppSec Researcher, I see this most often when developers use w.Write() with string concatenation instead of structured serialization.
The Vulnerable Pattern
func GetUser(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
// VULNERABLE: Direct reflection without Content-Type enforcement
// An attacker can pass as the name
w.Write([]byte("User: " + name))
}
The Secure Implementation
To remediate XSS in Chi APIs, follow the 'Data-as-Data' principle. 1. Explicitly set 'Content-Type: application/json' so browsers don't interpret the body as HTML. 2. Set 'X-Content-Type-Options: nosniff' to disable the browser's MIME-sniffing feature, which is the primary vector for XSS in APIs. 3. Use 'encoding/json' to serialize responses; this ensures that even if a payload contains HTML tags, they are treated as string literals within a JSON object. 4. Implement a global middleware to apply security headers like CSP and X-Content-Type-Options across all routes.
func GetUser(w http.ResponseWriter, r *http.Request) { name := chi.URLParam(r, "name")// SECURE: Enforce JSON and prevent MIME sniffing w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Content-Type-Options", "nosniff") response := map[string]string{"user": name} json.NewEncoder(w).Encode(response)}
// Global Middleware approach in Chi // r.Use(middleware.SetHeader(“X-Content-Type-Options”, “nosniff”)) // r.Use(middleware.SetHeader(“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.