Fix XSS in API Responses in Gin
Reflected XSS in Gin-based APIs occurs when untrusted input is echoed back in responses without proper sanitization or via incorrect Content-Type headers. Even in APIs, if a developer mistakenly uses c.HTML() or c.String() with user-controlled data, an attacker can inject malicious scripts that execute in the context of the victim's session. Stop trusting the client; start enforcing strict output encoding.
The Vulnerable Pattern
func VulnerableHandler(c *gin.Context) {
userInput := c.Query("user")
// DANGER: Directly injecting raw input into HTML template or raw string response
c.HTML(200, "profile.tmpl", gin.H{
"username": userInput,
})
// OR: c.String(200, "Welcome " + userInput + "
")
}
The Secure Implementation
The primary defense against XSS in Gin is ensuring responses are served as 'application/json'. When using c.JSON(), Gin utilizes Go's 'encoding/json' which automatically escapes HTML-sensitive characters like '<', '>', and '&' into Unicode sequences. This prevents the browser from interpreting the data as executable HTML/JavaScript. If you must serve HTML, rely on Gin's default 'html/template' engine which provides context-aware auto-escaping. Never use 'template.HTML()' to cast user-controlled strings, as this explicitly marks the content as safe and disables protection.
func SecureHandler(c *gin.Context) {
userInput := c.Query("user")
// SECURE: Use c.JSON() to force application/json and automatic character escaping
c.JSON(200, gin.H{
"status": "success",
"username": userInput,
})
// If HTML is required, ensure the template engine's auto-escaping is NOT bypassed.
}
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.