If you have multiple closely related domains for a single property you probably want to be permissive with CORS

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-11-23

I woke up and noticed tens of spurious-looking add-to-carts in my non-UK websites.

When I added to a product to the cart from my Irish website, caused nothing happened on the UI front. Nothing was added to cart. Inspecting the JavaScript errors, I saw that it failed due to CORS:

Access to XMLHttpRequest at 'https://www.oxbridgenotes.co.uk/orders/populate' from origin 'https://en-ie.oxbridgenotes.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The issue was that my button for adding to cart used a url for the wrong domain under my control, and that request failed because I had no CORS set up.

Lessons

  Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins Config::MY_DOMAINS.split(',').map { |origin| origin.strip }

      resource '*',
        headers: :any,
        methods: [:get, :post, :put, :patch, :delete, :options, :head]
    end
  end