0
0
Ruby on Railsframework~8 mins

CORS configuration in Ruby on Rails - Performance & Optimization

Choose your learning style9 modes available
Performance: CORS configuration
MEDIUM IMPACT
CORS configuration affects the browser's ability to load resources from different origins, impacting page load speed and interaction readiness.
Allowing cross-origin requests for API resources
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'https://trusted.example.com'
    resource '/api/*', headers: :any, methods: [:get, :post, :options]
  end
end
Restricting origins and resource paths reduces unnecessary preflight requests and network overhead, improving load speed and security.
📈 Performance GainEliminates many preflight requests, reducing network latency and speeding up LCP.
Allowing cross-origin requests for API resources
Ruby on Rails
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end
Using a wildcard '*' for origins allows all domains, triggering preflight requests and potential security risks, which can slow down loading.
📉 Performance CostTriggers preflight OPTIONS requests for every cross-origin call, adding network latency and blocking rendering until response.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Wildcard origins with broad resource accessMinimal0Low but delayed by network[X] Bad
Restricted origins and resource pathsMinimal0Low and fast[OK] Good
Rendering Pipeline
CORS configuration affects the browser's network request phase before rendering. If misconfigured, it causes extra preflight requests that delay resource loading and block rendering.
Network Request
Resource Loading
Rendering
⚠️ BottleneckNetwork Request due to preflight OPTIONS calls
Core Web Vital Affected
LCP
CORS configuration affects the browser's ability to load resources from different origins, impacting page load speed and interaction readiness.
Optimization Tips
1Avoid using '*' wildcard for origins in production CORS settings.
2Limit resource paths and HTTP methods allowed for cross-origin requests.
3Use DevTools Network tab to monitor and minimize preflight OPTIONS requests.
Performance Quiz - 3 Questions
Test your performance knowledge
What impact does using a wildcard '*' for origins in CORS have on page load?
AIt has no effect on performance.
BIt reduces network requests and speeds up loading.
CIt triggers many preflight requests, increasing load time.
DIt blocks all cross-origin requests.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by OPTIONS method, and observe preflight requests for cross-origin calls.
What to look for: Look for many OPTIONS requests before actual resource loads; fewer or no OPTIONS requests indicate better CORS performance.