Skip to Content
DocsIntegrationRuby on Rails

Ruby on Rails

To integrate ProxyTracer into a Rails application with maximum efficiency, we bypass the controller layer entirely and build a custom Rack Middleware. This intercepts the raw HTTP request before it enters the Rails router.

The Rack Middleware

This middleware leverages the native Rack::Request object to safely extract the IP (handling spoofed headers automatically) and uses Ruby’s standard Net::HTTP library to enforce a strict timeout.

require 'net/http' require 'json' class ProxyTracerMiddleware def initialize(app) @app = app @api_key = ENV['PROXYTRACER_API_KEY'] end def call(env) # 1. Extract the IP (Rack automatically sanitizes X-Forwarded-For) request = Rack::Request.new(env) ip = request.ip # Skip local development if ip && !['127.0.0.1', '::1'].include?(ip) begin uri = URI("https://api.proxytracer.com/v1/check/#{ip}") req = Net::HTTP::Get.new(uri) req['Authorization'] = "Bearer #{@api_key}" # 2. Query ProxyTracer API with a strict 500ms timeout response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 0.5) do |http| http.request(req) end if response.is_a?(Net::HTTPSuccess) data = JSON.parse(response.body) # 3. Drop the connection immediately if a proxy is detected if data['proxy'] == true return [ 403, { 'Content-Type' => 'application/json' }, ['{"error": "Access Denied: VPN or Proxy detected."}'] ] end end rescue StandardError => e # Fail open: Log the error and allow the request to proceed Rails.logger.error("ProxyTracer validation failed: #{e.message}") end end # 4. Traffic is clean, proceed down the Rack stack to the Rails router @app.call(env) end end

Configuration

To activate the protection globally, insert the middleware into your application stack inside config/application.rb:

module YourApp class Application < Rails::Application # ... # Insert it high up in the stack to reject bad traffic early config.middleware.insert_before Rack::Sendfile, ProxyTracerMiddleware # ... end end
Last updated on