GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Rails

XSS in Rails APIs occurs when unsanitized user input is reflected in responses that a browser can misinterpret as HTML. Even if you think you are serving JSON, improper MIME types or lack of 'nosniff' headers can allow an attacker to force the browser into executing malicious scripts via content sniffing.

The Vulnerable Pattern

class ProfilesController < ApplicationController
  def show
    @user = User.find(params[:id])
    # VULNERABLE: Reflecting raw input with 'render plain' or generic 'render text'
    # If @user.bio contains , it may execute if the browser sniffs HTML.
    render plain: "User Bio: #{@user.bio}"
  end
end

The Secure Implementation

To kill API-based XSS: 1. Always use 'render json:' which sets the 'Content-Type: application/json' header. 2. Rails' 'to_json' implementation automatically escapes HTML entities like '<', '>', and '&' to prevent injection into the DOM. 3. Globalize 'X-Content-Type-Options: nosniff' to block browsers from treating non-HTML content as executable scripts. 4. If you must return HTML/SVG fragments, use the Rails SanitizeHelper to whitelist safe tags and attributes, stripping all 'on*' event handlers and 'javascript:' URIs.

class ProfilesController < ApplicationController
  def show
    @user = User.find(params[:id])
    # SECURE: Force application/json and use Rails' built-in JSON escaping
    # Ensure ActionController::Base.helpers.sanitize is used if HTML is expected
    render json: { bio: ActionController::Base.helpers.sanitize(@user.bio) }, status: :ok
  end
end

config/initializers/security_headers.rb

Ensure the browser does not attempt to sniff the MIME type

Rails.application.config.action_dispatch.default_headers.merge!({ ‘X-Content-Type-Options’ => ‘nosniff’, ‘Content-Security-Policy’ => “default-src ‘none’; frame-ancestors ‘none’;” })

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