CORS (Cross-Origin Resource Sharing) is a browser mechanism that lets a server state which other origins may read its responses. Browsers stop JavaScript on one origin (scheme, domain and port) from reading responses from another origin, and the server relaxes that rule with headers such as Access-Control-Allow-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

What is CORS used for?

CORS is used when a front end and its API live on different origins, for example app.example.com calling api.example.com. The API sends Access-Control-Allow-Origin and related headers, and for some requests the browser first sends an OPTIONS preflight request to check them.

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.