0
0
Ruby on Railsframework~5 mins

CORS configuration in Ruby on Rails

Choose your learning style9 modes available
Introduction

CORS helps your web app share resources safely with other websites. It controls who can access your app's data from different places.

When your Rails API serves data to a frontend app on a different domain.
When you want to allow specific websites to use your API but block others.
When building a public API that many websites can access safely.
When your frontend and backend are on different servers or ports during development.
When you want to prevent security issues from unwanted cross-site requests.
Syntax
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'example.com'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end
Use origins to specify which websites can access your app.
The resource line controls which paths and HTTP methods are allowed.
Examples
This allows any website to access all resources with any HTTP method. Use carefully for public APIs.
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end
This allows only 'https://myfrontend.com' to access API routes with GET and POST methods.
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'https://myfrontend.com'
    resource '/api/*', headers: :any, methods: [:get, :post]
  end
end
This is useful during development when your frontend runs on localhost port 3000.
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000'
    resource '*', headers: :any, methods: [:get, :post, :patch, :delete, :options]
  end
end
Sample Program

This config allows a frontend running on http://localhost:3000 to make GET, POST, and OPTIONS requests to your Rails backend.

Ruby on Rails
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end
OutputSuccess
Important Notes

Always restrict origins to trusted domains in production for security.

Use methods to limit allowed HTTP actions to only what your app needs.

Remember to restart your Rails server after changing CORS settings.

Summary

CORS controls which websites can access your Rails app's resources.

Configure CORS in config/initializers/cors.rb using Rack::Cors.

Be careful to allow only trusted origins and needed HTTP methods.