What is cors?
CORS stands for Cross‑Origin Resource Sharing. It is a security mechanism built into web browsers that decides whether a web page can request resources (like data, images, or scripts) from a different website (a different “origin”) than the one it was loaded from.
Let's break it down
- Origin: The combination of a website’s protocol (http/https), domain name, and port. For example, https://example.com:443 is one origin.
- Same‑origin policy: By default browsers only allow a page to talk to its own origin. This stops a malicious site from stealing data from another site.
- CORS headers: The server can add special HTTP headers (e.g., Access‑Control‑Allow‑Origin) to tell the browser “it’s okay for this other origin to access my resources.”
- Preflight request: For some “complex” requests (like using PUT or custom headers), the browser first sends an OPTIONS request to ask the server if the real request is allowed. The server’s response decides whether the actual request proceeds.
Why does it matter?
CORS protects users by preventing unauthorized sites from reading sensitive data from another site, while still letting developers share public APIs and assets across domains. Without CORS, any website could freely pull data from any other site, opening the door to data theft and cross‑site attacks.
Where is it used?
- Public APIs (e.g., weather, map, or social‑media services) that need to be called from web apps hosted on different domains.
- Content Delivery Networks (CDNs) that serve images, fonts, or JavaScript to many websites.
- Single‑page applications (React, Angular, Vue) that talk to a backend server located on another domain or sub‑domain.
- Browser extensions or mobile web views that load external resources.
Good things about it
- Fine‑grained control: Servers can specify exactly which origins, methods, and headers are allowed.
- Enables modern web apps: Makes it possible to build decoupled front‑ends and back‑ends that live on separate domains.
- Standardized: It’s part of the HTTP specification, so all major browsers support it consistently.
- Improves security: Reduces the risk of accidental data leakage by defaulting to “blocked” unless explicitly permitted.
Not-so-good things
- Complexity: Understanding preflight requests, header combinations, and error messages can be confusing for beginners.
- Configuration headaches: A small mistake (like a missing header or wrong wildcard) can break an API call, leading to frustrating debugging.
- Performance impact: Preflight OPTIONS requests add extra network round‑trips for certain calls, which can slow down the app.
- Over‑reliance on browsers: CORS only protects browsers; other clients (like server‑to‑server scripts) are not restricted, so developers must still enforce proper authentication.