Rails API-only app setup for React frontend
Maya Patel
Jan 2026
2 tabs
module MyApp
class Application < Rails::Application
config.load_defaults 6.1
# API-only mode
config.api_only = true
# CORS configuration
config.middleware.insert_before 0, Rack::Cors do
allow do
origins_list = if Rails.env.production?
ENV['FRONTEND_URL']
else
'localhost:5173', 'localhost:3001', /127\.0\.0\.1:\d+/
end
origins origins_list
resource '/api/*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
credentials: true,
expose: ['Authorization']
end
end
end
end
class ApplicationController < ActionController::API
include ActionController::Cookies
before_action :set_default_format
private
def set_default_format
request.format = :json
end
end
2 files · ruby
Explain with highlit
When building a React SPA, I configure Rails in API-only mode to skip view rendering, asset pipeline, and session cookies. The --api flag generates a lean Rails app focused on JSON responses. I enable CORS to allow the React dev server on localhost:5173 to communicate with Rails during development, while restricting origins in production. The rack-cors gem handles preflight OPTIONS requests automatically. I also configure Rails to use token-based authentication instead of session cookies since SPAs can't rely on same-origin cookie behavior. This setup provides a clean separation between backend API concerns and frontend presentation logic, making both easier to scale and deploy independently.