Enable CORS in Rails
12 April 2022 (Updated 1 October 2023)
On this page
Install rack-cors
gem
Add to Gemfile:
gem 'rack-cors'
Run:
./bin/bundle install
Configure CORS policy
Edit config/initializers/cors.rb
:
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins Rails.application.config.frontend_url
resource '*',
headers: :any,
methods: %i[get post put patch delete options head]
end
end
Edit config/environments/development.rb
and config/environments/test.rb
to allow access from all hosts when running in the development
and test
environments:
Rails.application.configure do
# other config
config.frontend_url = '*'
end
Edit config/environments/production.rb
to restrict access to specific host in the production environment
:
Rails.application.configure do
# other config
config.frontend_url = ENV.fetch('FRONTEND_URL')
end
You’ll want to set the FRONTEND_URL
as an environment variable in your production server.
Restart your dev server to activate the new CORS policy.
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment