CORS
suggest changeCross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web applications running at one origin (domain, protocol, or port) from making requests to resources hosted on a different origin. When building API backends in Ruby, you must configure CORS headers so client-side frontend applications (such as React, Vue, or mobile web views) can access your endpoints.
How CORS Works
- Simple Requests: For basic GET or POST requests with standard content types, browsers send the request with an
Originheader. The server responds withAccess-Control-Allow-Origin. - Preflight Requests: For requests that modify data (PUT, DELETE, PATCH) or include custom headers (such as
Authorization: Bearer <token>orContent-Type: application/json), browsers first send an HTTPOPTIONSpreflight request to verify server permissions before sending the actual request.
Using rack-cors Middleware
The standard, idiomatic way to handle CORS in Ruby is the rack-cors gem. Because almost all modern Ruby web frameworks (Sinatra, Hanami, Rails, and Roda) are built on top of Rack, rack-cors works seamlessly across them.
Install the gem:
gem install rack-cors
Or add it to your Gemfile:
gem 'rack-cors', require: 'rack/cors'
Configuring in config.ru (Rack, Sinatra, Hanami)
In your application's config.ru (or framework middleware stack):
require 'rack'
require 'rack/cors'
require_relative 'app'
use Rack::Cors do
# Allow requests from frontend development servers and production domains
allow do
origins 'localhost:3000', 'https://myapp.example.com'
resource '/api/*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
credentials: true,
max_age: 86400 # Cache preflight response for 24 hours
end
# Public read-only endpoints allowing any origin
allow do
origins '*'
resource '/public/*',
headers: :any,
methods: [:get, :options]
end
end
run App.new
Key Configuration Options
origins: Accepts string literals, regular expressions (e.g.,/https:\/\/.*\.example\.com/), or blocks that inspect the origin dynamically.resource: URL path pattern to protect (supports wildcards like*).headers: Allowed HTTP request headers (:anyallows all).methods: List of allowed HTTP methods (:get,:post,:put, etc.).credentials: Set totrueif cookies or HTTP authentication headers should be supported cross-origin. Note: Whencredentials: true,originscannot be'*'.max_age: Number of seconds browsers may cache the preflight response to avoid redundantOPTIONSround trips.
Pure Rack Implementation
If you want to handle CORS manually without external gems, you can create a custom Rack middleware:
class CorsMiddleware
def initialize(app, allowed_origin: '*')
@app = app
@allowed_origin = allowed_origin
end
def call(env)
# Intercept HTTP OPTIONS preflight request
if env['REQUEST_METHOD'] == 'OPTIONS'
return [204, cors_headers, []]
end
status, headers, body = @app.call(env)
[status, headers.merge(cors_headers), body]
end
private
def cors_headers
{
# Rack 3 requires lowercase header names
'access-control-allow-origin' => @allowed_origin,
'access-control-allow-methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers' => 'Content-Type, Authorization, X-Requested-With',
'access-control-max-age' => '86400'
}
end
end
Security Best Practices
- Avoid Wildcard (
*) in Production: Never useorigins '*'for endpoints that return sensitive user data or require credentials. - Dynamic Origin Validation: When supporting multiple dynamic domains, match against an allowlist rather than blindly echoing back the incoming
Originheader. - Expose Necessary Response Headers: By default, browsers only expose a few safe response headers to JavaScript. If your client needs to read custom headers (like
X-Total-CountorAuthorization), specify them usingexpose: ['X-Total-Count'].