Course contentsShow
← Web Development
Lesson 860 of 2,98215. Browser NetworkingFree lesson

What is CORS and Why It Exists

Understanding the Same-Origin Policy and why browsers enforce CORS for cross-origin requests.

What is CORS and Why It Exists

You'll learn why browsers block some web requests between different websites and how CORS provides a safe workaround.

The Same-Origin Policy: A Security Wall

Imagine your browser as a security guard that only allows websites to talk to their own servers by default. This guard follows the Same-Origin Policy — a fundamental browser security measure.

An "origin" consists of three parts: protocol (http/https), domain (example.com), and port (80, 443, etc.). If all three match, it's the same origin. If any differ, it's cross-origin.

For example:

  • https://myapp.com/page1 and https://myapp.com/page2 → same origin ✓
  • https://myapp.com and https://api.differentsite.com → cross-origin ✗

Why Browsers Block Cross-Origin Requests

Without this protection, a malicious website could use JavaScript to read your Gmail emails, access your bank account, or steal data from any site where you're logged in — all from your browser, using your cookies and credentials. The Same-Origin Policy prevents this by blocking JavaScript from reading responses from different origins.

Enter CORS: Controlled Cross-Origin Access

CORS (Cross-Origin Resource Sharing) is the mechanism that allows servers to explicitly permit cross-origin requests. It's like the server saying: "Browser, I know this request is coming from a different website, but I trust it — let it through."

The server communicates this permission through special HTTP headers (like Access-Control-Allow-Origin) that tell the browser which origins are allowed to access its resources.

Key Takeaway: CORS exists because the Same-Origin Policy blocks cross-origin requests by default for security, and CORS provides a standardized way for servers to safely opt-in to cross-origin sharing when appropriate.