🌐 Understanding CORS in Ruby on Rails: A Beginner’s Guide 🚀

Lakhveer Singh Rajput
3 min readAug 9, 2024

--

In this article, we will learn about the CORS, and its implementation using Ruby on Rails. Cross-Origin Resource Sharing (CORS) is an essential concept for web developers, especially when dealing with APIs and frontend-backend communication. If you’re building a Ruby on Rails application that interacts with a frontend framework like React or a mobile app, you’ll likely encounter CORS. Let’s dive into what CORS is, why it matters, and how to configure it in a Rails application.

🧠 What is CORS?

CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented by web browsers to restrict how resources on a web page can be requested from another domain (origin) than the one the page was served from.

For example, if your Rails API is hosted at api.example.com and your frontend is served from app.example.com, CORS ensures that only the requests you want to allow from app.example.com can access your API. Without CORS, your API could be vulnerable to malicious requests from other domains.

🤔 Why is CORS Important?

CORS is crucial because it helps maintain the security and integrity of your web applications. By controlling which origins can access your resources, CORS helps prevent Cross-Site Request Forgery (CSRF) and other potential security threats.

⚙️ Setting Up CORS in a Rails Application

Let’s walk through the steps to set up CORS in a Ruby on Rails application:

Add the CORS Gem 🛠️

First, you’ll need to add the rack-cors gem to your Rails project. This gem helps handle CORS requests.

# Gemfile 
gem 'rack-cors'

After adding the gem, run bundle install to install it.

Configure CORS Middleware 🔧

Next, you’ll configure the middleware in your config/application.rb or a specific environment file like config/environments/development.rb.

# config/application.rb

module YourApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1

# CORS configuration
config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000' # Replace with your frontend URL

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

In this example:

  • origins specifies the domains that are allowed to access your API. You can set it to 'http://localhost:3000' for development or your frontend’s domain in production.
  • resource specifies which resources can be accessed and the allowed HTTP methods (GET, POST, etc.).
  • credentials: true allows cookies to be sent with requests, which is important for authentication.

Test Your Configuration

Once you’ve set up CORS, test it by making a request from your frontend or a tool like Postman. If configured correctly, your Rails API should respond with the appropriate CORS headers.

For example, a successful response might include headers like:

Access-Control-Allow-Origin: http://localhost:3000 
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS

🌟 Tips & Best Practices

  • Use Environment Variables 🌍: Instead of hardcoding URLs in your configuration, consider using environment variables to manage different origins for development, staging, and production.
  • Limit Access 🔒: Be as restrictive as possible with the origins and methods you allow. This minimizes potential security risks.
  • Understand the Options Request 📡: Browsers send a preflight OPTIONS request to check CORS settings before making the actual request. Ensure your server handles this correctly by allowing the OPTIONS method in your CORS configuration.

🚀 Conclusion

CORS might seem complex at first, but with the right configuration, it’s a powerful tool to ensure secure communication between your frontend and backend. By using the rack-cors gem in your Ruby on Rails application, you can easily manage cross-origin requests and protect your application from potential security threats.

Happy coding! 💻✨

--

--

Lakhveer Singh Rajput
Lakhveer Singh Rajput

Written by Lakhveer Singh Rajput

Ruby on Rails enthusiast, book lover and DevOps explorer. Follow me for insights on coding, book recommendations, and bridging development with operations.🚀📚

No responses yet