How to fix XSS in API Responses
in Plug
Executive Summary
XSS in APIs occurs when an endpoint reflects untrusted input in a response without proper content-type enforcement or encoding. In Elixir's Plug, if you return user data with a 'text/html' header or fail to specify a type, a browser may execute malicious scripts embedded in the payload. Secure your pipeline by enforcing strict JSON types and security headers.
The Vulnerable Pattern
defmodule MyApp.VulnerablePlug do
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
# VULNERABLE: Reflecting input directly into a response with potential HTML context
user_id = conn.params[“id”]
conn
|> put_resp_content_type(“text/html”)
|> send_resp(200, “
User ID: #{user_id}”)
end
end
The Secure Implementation
The fix involves three layers of defense. First, change the 'Content-Type' to 'application/json', which tells the browser to treat the body as data rather than executable markup. Second, use 'Jason.encode!' to ensure that any special characters like <, >, or & are safely handled within the JSON string. Third, set the 'X-Content-Type-Options: nosniff' header to prevent the browser from attempting to 'sniff' the MIME type and potentially executing the payload as HTML if it finds HTML-like tags in the body.
defmodule MyApp.SecurePlug do import Plug.Conndef init(opts), do: opts
def call(conn, _opts) do # SECURE: Force application/json and use a JSON library to encode data user_id = conn.params[“id”] response_body = Jason.encode!(%{user_id: user_id})
conn |> put_resp_content_type("application/json") |> put_resp_header("x-content-type-options", "nosniff") |> put_resp_header("x-frame-options", "DENY") |> send_resp(200, response_body)
end 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.