I am using the rack-cors gem with a Rail 5.1 API.
I have the following initializer as per the documentation:
config/initializers/cors.rb
module Api
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins ['http://localhost:4200','https://app.mydomain.com/']
resource '*',
headers: :any,
:expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
end
However, this means that when deployed to production my api will accept requests from any localhost:4200
origin.
How can I separate these settings out so that different environments can have different allowed origins?
The easiest way to configure CORS on your Rails app is to use rack-cors gem. You can install it like any other gem, by executing: Next, you need to provide the configuration for the gem. You need to inform Rails which origin it should allow. To do that, you need to create a new initializer for your application.
The config/database.yml file contains sections for three different environments in which Rails can run by default: The development environment is used on your development/local computer as you interact manually with the application. The test environment is used when running automated tests.
In the most simple scenario, CORS will block all requests from a different origin than your API. “Origin” in this case is the combination of protocol, domain, and port. If any of these three will be different between the front end and your Rails application, then CORS won’t allow the client to connect to the API.
The configuration file config/application.rb and environment-specific configuration files (such as config/environments/production.rb) allow you to specify the various settings that you want to pass down to all of the components. For example, you could add this setting to config/application.rb file: This is a setting for Rails itself.
There are a few different options. One is to use secrets.yml
file. There you can define different values per environment, let's say:
development:
allowed_origins:
- http://localhost:4200
production:
allowed_origins:
- http://productionurl1.com
- http://productionurl2.com
Then in your configuration file you can do
module Api
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins Rails.application.secrets.allowed_origins
end
end
end
Another option (taken from the comments) is to use the environment files, eg:
development.rb
config.allowed_cors_origins = ["http://localhost:4200"]
Then in the cors.rb
initializer you can do:
Rails.application.config.allowed_cors_origins
(since initializer will be called after the environment config file, this should work).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With