rack-cors icon indicating copy to clipboard operation
rack-cors copied to clipboard

how can i add multiple origins in rack-cors

Open deepaksisodiaa opened this issue 6 years ago • 7 comments

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'http://localhost:3000, http://localhost:4000' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end

deepaksisodiaa avatar Jan 21 '19 06:01 deepaksisodiaa

https://github.com/cyu/rack-cors/issues/131

jkeam avatar May 23 '19 19:05 jkeam

As specified in #131 you'll have to add multiple allow block entries to configure different origins, e.g.

allowed_headers = %i(get post put patch delete options head)
allow do
  origins 'http://localhost:3000'
  resource '*', headers: :any, methods: allowed_headers
end

allow do
  origins 'http://localhost:4000'
  resource '*', headers: :any, methods: allowed_headers
end

camallen avatar Nov 21 '19 10:11 camallen

This would be a good addition to the README!

dchersey avatar Mar 23 '20 21:03 dchersey

The original post is passing a single string with a comma separated list to origins

origins 'http://localhost:3000, http://localhost:4000'

that is incorrect. origins takes multiple arguments. You should be passing multiple args as shown in the README:

https://github.com/cyu/rack-cors#rack-configuration

use Rack::Cors do
  allow do
    origins 'localhost:3000', '127.0.0.1:3000',
            /\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/
            # regular expressions can be used here

The code loops through the origins and checks each for a match https://github.com/cyu/rack-cors/blob/dbea904a7767aef89f48686635add60157144d42/lib/rack/cors/resources.rb#L42-L50

So you should be passing

origins 'http://localhost:3000', 'http://localhost:4000'

(passing 2 strings as opposed to passing 1 comma separated string)

rally25rs avatar Apr 16 '20 12:04 rally25rs

How can we pass an environment variable to origins?

The environment variable must be a string so separate the domains by a whitespace. Environment variable:
CORS_ORIGINS = 'domain1.com domain2.com anotherone.com'

origins ENV.fetch('CORS_ORIGINS').split(" ").map { |e| "'#{e.strip}'" }.join(", ").tr('"', "")

Yields: "'domain1.com', 'domain2.com', 'anotherone.com'"

This won't work because it is a string instead of a comma separated list. One way to get this to work is to loop through the values similar to Cam's answer

cickes avatar Feb 26 '21 19:02 cickes

@cickes try this:

origin *ENV.fetch('CORS_ORIGINS').split(" ").map(&:strip)

cyu avatar Mar 02 '21 04:03 cyu

I'm doing some issue gardening 🌱🌿 🌷 and came upon this issue. Since it's quite old I just wanted to ask if this is still relevant? If it isn't, maybe we can close this issue?

By closing some old issues we reduce the list of open issues to a more manageable set.

sandstrom avatar Mar 02 '22 18:03 sandstrom