GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Grape

APIs are often overlooked in XSS audits, but they are prime targets for reflected payloads. In the context of Grape, XSS occurs when an endpoint accepts user input and reflects it back in the response body without proper encoding or with an insecure Content-Type header. If a browser is tricked into rendering the API response as HTML, any embedded script will execute in the context of the domain.

The Vulnerable Pattern

class VulnerableAPI < Grape::API
  format :txt
  content_type :html, 'text/html'

get ‘/search’ do # DIRECT INJECTION: User input is reflected without sanitization # Content-Type is set to text/html, allowing script execution content_type ‘text/html’ “

Search results for: #{params[:query]}

” end end

The Secure Implementation

To kill XSS in Grape: 1) Avoid 'text/html' content types; stick to 'application/json' which browsers won't execute as script. 2) Use the 'X-Content-Type-Options: nosniff' header to stop MIME-type sniffing attacks where browsers try to guess if a response is HTML. 3) Always escape dynamic data using 'ERB::Util.html_escape' or a dedicated sanitization library before reflection. 4) Deploy a restrictive Content Security Policy (CSP) to block unauthorized inline scripts.

class SecureAPI < Grape::API
  format :json

helpers do def clean(text) # Escape HTML entities ERB::Util.html_escape(text) end end

get ‘/search’ do # 1. Enforce application/json to prevent browser rendering # 2. Sanitize data even if it is intended for JSON # 3. Implement security headers header ‘X-Content-Type-Options’, ‘nosniff’ header ‘Content-Security-Policy’, “default-src ‘none’; frame-ancestors ‘none’”

{ 
  results: "Search results for: #{clean(params[:query])}",
  status: "success"
}

end end

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