CORS

Fix CORS Error in Ruby on Rails

Updated April 2026

Reading this article? Verify your fix in real-time. Test your Rails CORS config live → CORSFixer

Rails API mode does not allow cross-origin requests by default. The rack-cors gem handles it — it is already in your Gemfile if you generated an API-only app, just uncommented.

Browser Console
Access to fetch at 'https://api.yourapp.com/users' from origin 'https://yourapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Step 1 — Uncomment rack-cors in Gemfile

# Gemfile — it is already there in API apps, just commented out
gem "rack-cors"
bundle install

Step 2 — Configure in application.rb

# config/application.rb
module YourApp class Application < Rails::Application config.middleware.insert_before 0, Rack::Cors do allow do origins "https://yourapp.com", "https://staging.yourapp.com" resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head], credentials: false end end end
end

With credentials (JWT cookies or session auth)

config.middleware.insert_before 0, Rack::Cors do allow do origins "https://yourapp.com"  # must be explicit, not wildcard resource "/api/*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options], credentials: true,  # allows cookies and Authorization header max_age: 86400 end
end

Multiple origin patterns

config.middleware.insert_before 0, Rack::Cors do allow do origins "https://yourapp.com", "https://staging.yourapp.com", /\Ahttps:\/\/.*\.yourapp\.com\z/  # regex for subdomains resource "/api/*", headers: :any, methods: :any end
end

Restrict by route prefix

config.middleware.insert_before 0, Rack::Cors do # Public API — allow all origins allow do origins "*" resource "/api/public/*", headers: :any, methods: [:get] end # Private API — restrict to your frontend allow do origins "https://yourapp.com" resource "/api/*", headers: :any, methods: :any, credentials: true end
end

Test the preflight

curl -X OPTIONS https://api.yourapp.com/api/users \ -H "Origin: https://yourapp.com" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Authorization" -v
Test your Rails CORS config live → CORSFixer