ruby 17 lines · 1 tab

CORS configuration for cross-origin API requests

Alex Kumar Jan 2026
1 tab
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins_list = if Rails.env.production?
                     ENV['CORS_ALLOWED_ORIGINS']&.split(',') || []
                   else
                     'localhost:3000', 'localhost:5173', /127\.0\.0\.1:\d+/
                   end

    origins origins_list

    resource '/api/*',
             headers: :any,
             methods: [:get, :post, :put, :patch, :delete, :options, :head],
             credentials: true,
             max_age: 86400
  end
end
1 file · ruby Explain with highlit

When building APIs consumed by frontend applications hosted on different domains, CORS (Cross-Origin Resource Sharing) headers are mandatory. The rack-cors gem simplifies configuration by letting me whitelist specific origins, HTTP methods, and headers. For development, I allow localhost with any port, while production configurations specify exact frontend domains. The credentials: true option allows cookies and authorization headers to be sent with requests, which is essential for authentication flows. I also configure max_age to reduce preflight OPTIONS requests for frequently accessed endpoints. Misconfigured CORS is a common source of frustration, so I verify the configuration using browser dev tools and explicit curl commands with origin headers.


Related snips

Share this code

Here's the card — post it anywhere.

CORS configuration for cross-origin API requests — share card
Link copied