GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Echo

XSS in Go-based APIs often occurs when developers bypass standard serialization in favor of manual string concatenation or improper content-type handling. In the Echo framework, reflecting raw query parameters into HTML or non-JSON responses creates a direct injection vector for client-side script execution. If the Content-Type isn't strictly enforced or if user input is rendered in an HTML context, the API becomes a delivery mechanism for malicious payloads.

The Vulnerable Pattern

e.GET("/search", func(c echo.Context) error {
	query := c.QueryParam("q")
	// VULNERABLE: Manual string concatenation in HTML response
	return c.HTML(http.StatusOK, "Results for: " + query + "")
})

The Secure Implementation

The vulnerable code uses c.HTML to reflect raw user input. An attacker providing '?q=' triggers immediate execution in the victim's browser. The fix involves two layers: First, utilize c.JSON() for API responses; it uses Go's json.Marshal which escapes characters like '<', '>', and '&' to their unicode equivalents (e.g., \u003c). Second, if HTML must be served, use the 'html/template' package via c.Render() which provides context-aware escaping. Finally, always apply the 'nosniff' header to prevent browsers from interpreting non-HTML content-types as HTML.

e.GET("/search", func(c echo.Context) error {
	query := c.QueryParam("q")
// SECURE OPTION 1: Use c.JSON() which automatically escapes HTML entities
// return c.JSON(http.StatusOK, map[string]string{"query": query})

// SECURE OPTION 2: Use html/template for contextual auto-escaping
return c.Render(http.StatusOK, "search.html", map[string]interface{}{
	"query": query,
})

})

// Global Middleware to prevent MIME sniffing e.Use(middleware.SecureWithConfig(middleware.SecureConfig{ XContentTypeOptions: “nosniff”, }))

System Alert • ID: 5423
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.