📌 What is CORS?

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a web page can access resources from a different origin.

By default, browsers block cross-origin reads unless the target server explicitly allows them.

📌 Goal

Prevent malicious websites from reading sensitive data from another website.

Example:

Prevent evil.com from reading your logged-in banking session.


🧩 Core Concepts

1️⃣ What is an Origin?

An Origin = Combination of:

Origin = Protocol + Domain + Port

Example:

URLOrigin
https://om-mapari.comhttps + om-mapari.com + 443
http://om-mapari.comDifferent
https://leetcode.comDifferent
https://om-mapari.com:3001Different

Rule

If any one changes:

  • Protocol
  • Domain
  • Port → Browser treats it as Cross-Origin

2️⃣ Same-Origin Policy (SOP)

Browsers enforce Same-Origin Policy (SOP).

Rule

A website can only freely access:

Same Protocol
Same Domain
Same Port

Otherwise:

Browser blocks access

Why?

Without SOP:

evil.com

Read gmail.com
Read bank account
Steal session data

🔥 CORS Flow (LeetCode Example)

Scenario

You want to show your solved LeetCode solved count on your portfolio.

Portfolio:
https://om-mapari.com
 
API:
https://leetcode.com

Since domains differ:

Cross-Origin Request

Browser Request Lifecycle

┌──────────────────────────────┐
│ Portfolio (om-mapari.com)    │
└──────────────┬───────────────┘

               │ fetch()

┌──────────────────────────────┐
│ Browser                      │
│ Adds: Origin Header          │
│ Origin: om-mapari.com        │
└──────────────┬───────────────┘


┌──────────────────────────────┐
│ LeetCode Server              │
│ Processes Request            │
└──────────────┬───────────────┘

               │ Missing Header in Response ❌ 
               │ "Access-Control-Allow-Origin: https://om-mapari.com"

┌──────────────────────────────┐
│ Browser Validates Headers    │
└──────────────┬───────────────┘


❌ CORS Error
(JS cannot access response)

🛠️ How CORS Errors Are Resolved

Server explicitly allows trusted domains.

Access-Control-Allow-Origin: https://om-mapari.com

Browser:

Origin matches

Request allowed ✅

Method 2: Allow Everyone (Public APIs)

Use wildcard.

Access-Control-Allow-Origin: *

Meaning:

Any website can access

⚠️ Usually not used with authenticated requests.


Method 3: Backend Proxy (Most Common)

Instead of browser → external API:

Browser

Your Backend

External API

Because:

Server-to-server
No CORS restrictions

Flow:

Browser

your-api.com

leetcode.com

Method 4: Configure Reverse Proxy

Example:

Browser

Nginx

API

Proxy injects CORS headers.


🧠 Flashcards

Q: What defines an Origin?
Protocol + Domain + Port

Q: Who enforces CORS?
Browser

Q: Does CORS stop request execution?
No → only blocks JS access

Q: Do backend-to-backend requests have CORS?
No