What Is CORS?
Cross-Origin Resource Sharing
CORS is a browser security mechanism that controls which websites can make requests to your API. It uses HTTP headers to tell browsers whether a frontend at one origin (domain) is allowed to access resources from a different origin.
How CORS Works
By default, browsers block requests from one origin (like app.com) to a different origin (like api.com). This is the same-origin policy — a critical security feature. CORS relaxes this policy in a controlled way by having the server declare which origins are allowed.
When your React app on localhost:3000 calls your API on localhost:8080, the browser sends a preflight OPTIONS request first. Your server must respond with Access-Control-Allow-Origin headers granting permission, or the browser blocks the request.
Why Developers Use CORS
Every frontend developer encounters CORS errors. The fix is always on the server side — add the right headers. In Express, use the cors middleware. In Django, use django-cors-headers. In production, configure your reverse proxy (Nginx, Cloudflare) to handle CORS.
Key Concepts
- Same-Origin Policy — The browser security rule that CORS relaxes — by default, scripts can only fetch from their own origin
- Preflight Request — An OPTIONS request the browser sends automatically before certain cross-origin requests to check permissions
- Access-Control-Allow-Origin — The response header that specifies which origins can access the resource — set to specific domains, not '*' in production
- Credentials — CORS blocks cookies and auth headers by default on cross-origin requests — you must explicitly enable them
Frequently Asked Questions
Why do I get CORS errors?
Your backend isn't sending the right Access-Control-Allow-Origin header. Add CORS middleware to your server — cors() in Express, django-cors-headers in Django, or configure your reverse proxy.
Is CORS a security feature?
Yes, CORS protects users from malicious sites making requests on their behalf. It's enforced by the browser — API tools like curl or Postman ignore CORS entirely.