How to fix XSS in API Responses
in Phoenix
Executive Summary
XSS in Phoenix APIs typically occurs when a developer manually constructs a response body using user-controlled input and fails to strictly enforce the 'application/json' content-type. If a browser can be tricked into sniffing the response as 'text/html', any reflected payload will execute in the victim's session context.
The Vulnerable Pattern
def search(conn, %{"q" => query}) do
# VULNERABLE: Manual string interpolation and potentially weak content-type
# If an attacker sends ?q=, it reflects raw.
conn
|> put_resp_content_type("text/html")
|> send_resp(200, "{\"results\": [], \"query\": \"#{query}\"}")
end
The Secure Implementation
To kill API-based XSS in Phoenix, you must ensure three things: 1. Content-Type Integrity: Use the `json/2` helper or `render(conn, "index.json", data)` to force `application/json`. This prevents browsers from interpreting the response as HTML. 2. Proper Encoding: Never use string interpolation (`#{}`) to build JSON. Use `Jason` or `Poison` to serialize maps, ensuring special characters like <, >, and & are handled. 3. Defense in Depth: Ensure your pipeline calls `plug :put_secure_browser_headers` which includes `X-Content-Type-Options: nosniff`, preventing the browser from ignoring the JSON content-type and 'sniffing' for executable HTML.
def search(conn, %{"q" => query}) do
# SECURE: Use the json/2 helper which enforces application/json
# and uses the Jason library to properly encode/escape the payload.
conn
|> put_status(:ok)
|> json(%{results: [], query: query})
end
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.