GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Sinatra

Reflected XSS in API endpoints occurs when untrusted input is echoed back in the response without proper sanitization or content-type enforcement. In Sinatra, failing to explicitly set the JSON content type can lead browsers to sniff the payload as HTML, executing malicious scripts. Stop trusting the client; harden your headers.

The Vulnerable Pattern

get '/api/greet' do
  # VULNERABLE: Implicitly returns text/html or allows sniffing
  # If user passes ?name=, it executes in-browser
  user_name = params[:name]
  "{\"message\": \"Hello #{user_name}\"}"
end

The Secure Implementation

The vulnerability stems from MIME-sniffing and lack of output encoding. If the 'Content-Type' is missing or set to 'text/html', browsers may execute embedded scripts. Fix: 1. Explicitly set 'content_type :json' to tell the browser the payload is data, not executable code. 2. Set 'X-Content-Type-Options: nosniff' to prevent the browser from attempting to bypass the header via content analysis. 3. Always use '.to_json' which handles necessary character escaping, rather than manual string interpolation.

before do
  # Global hardening: Force JSON and disable sniffing
  content_type :json
  response.headers['X-Content-Type-Options'] = 'nosniff'
end

get ‘/api/greet’ do

SECURE: Data is JSON-encoded and served with correct headers

{ message: “Hello #{params[:name]}” }.to_json end

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