# Same-Origin Policy and CORS: Why Your Browser Said No

You build a small web page. It asks your API for some data. The browser console answers with a red error:

```text
Access to fetch at 'http://127.0.0.1:8001/' from origin 'http://127.0.0.1:8000'
has been blocked by CORS policy
```

Your first instinct is to make the error go away. Before you do, it helps to understand what the browser is protecting and who it is protecting.

---

## Start With the Origin

An **origin** is the combination of three things in a web address: the scheme (such as `https`), the host (such as `app.example.com`), and the port.

Two addresses share an origin only when all three match. Here is how some addresses compare to `https://app.example.com/page`:

| Address | Same origin? | Why |
| --- | --- | --- |
| `https://app.example.com/other` | Yes | Only the path differs |
| `http://app.example.com/page` | No | Different scheme |
| `https://app.example.com:8443/page` | No | Different port |
| `https://api.example.com/page` | No | Different host |

Notice that `api.example.com` is a different origin from `app.example.com`, even though both belong to the same company. That surprises many beginners.

---

## The Same-Origin Policy

The same-origin policy is a browser rule that limits how a page from one origin can interact with content from another.

MDN Web Docs describes the pattern like this:

- Cross-origin **writes** are typically allowed. Links, redirects, and form submissions are examples.
- Cross-origin **embedding** is typically allowed. Images, scripts, and frames are examples.
- Cross-origin **reads** are typically disallowed.

The reads rule is the important one. Your browser holds your logged-in sessions for many sites. Without this rule, any page you open could ask another site for your data and read the answer.

If you have read [Cookies and Sessions: How a Website Remembers You](ADD-HASHNODE-URL), you can see why that would be a problem.

---

## What CORS Adds

Sometimes a different origin should be allowed to read your data. A front end at `app.example.com` may legitimately call an API at `api.example.com`.

Cross-Origin Resource Sharing (CORS) is how a server says so. The server includes a header such as:

```http
Access-Control-Allow-Origin: https://app.example.com
```

That header tells the browser, "A page from this origin may read this response."

For some requests, the browser first sends a preflight. That is a request using the `OPTIONS` method, asking the server whether the real request is allowed. We cover methods in [HTTP Methods and Status Codes: Reading the Web's Conversation](ADD-HASHNODE-URL).

---

## What CORS Is Not

This is where most confusion lives. The Open Worldwide Application Security Project (OWASP) CORS Security Cheat Sheet is direct about it.

**CORS is not access control.** The browser enforces it, and only for scripts running in a browser. Any other client can send any `Origin` header it likes.

**CORS does not prevent cross-site request forgery (CSRF).** Some cross-origin requests, such as form posts, can still be processed by the server even when the page cannot read the response.

**CORS is not a substitute for authentication or authorization.** The cheat sheet's advice is to authenticate and authorize every request on the server as if CORS did not exist.

Plain version: CORS protects a user's browser from other websites. It does not protect your server from clients.

You will see this proven in the exercise below.

---

## Risky CORS Configurations

OWASP calls out several mistakes that beginners often make while trying to silence the error.

- **Reflecting the** `Origin` **header without checking it.** If a server echoes back whatever origin asks, combined with `Access-Control-Allow-Credentials: true`, any website may be able to read authenticated responses.
- **Trusting** `null`**.** Sandboxed documents and some local files send `Origin: null`, and any site can create such a document.
- **Using** `*` **with credentials.** Browsers reject a wildcard on requests that carry credentials. The unsafe workaround is reflecting the origin, which is the first mistake again.

The safer pattern is a fixed allowlist of exact origins. The server echoes an origin back only when it matches the list exactly.

A wildcard is reasonable only for genuinely public data with no credentials involved.

---

## Common Misconceptions

### "A CORS error means my server is broken."

It usually means the response did not carry permission for that origin. The server may have worked perfectly.

### "CORS stops attackers from calling my API."

It does not. Attackers do not need a browser. See [Authentication vs. Authorization: Why the Difference Matters](ADD-HASHNODE-URL).

### "The fix is to allow everything."

That can turn a harmless error into a data exposure. Decide which origins you trust with user data, and list them.

### "CORS replaces security headers."

It is one of several browser-enforced controls. [HTTP Security Headers: The Tiny Lines Doing a Lot of Work](ADD-HASHNODE-URL) covers others, like Content Security Policy.

### "If curl works, the browser should too."

`curl` ignores CORS entirely. The policy lives in the browser.

---

## Practical Exercise: See CORS From Both Sides

This lab needs a browser, so run it on your own computer or on a VM with a desktop. Both servers listen on `127.0.0.1` only.

Create a new empty folder for the lab. The simple web server below serves every file in the folder it runs from.

**Step 1: Save this as** `api_server.py`

```python
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

ALLOWED_ORIGIN = "http://127.0.0.1:8000" if "--allow" in sys.argv else None


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        if ALLOWED_ORIGIN:
            self.send_header("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
        self.end_headers()
        self.wfile.write(b'{"message": "hello from the API"}\n')


HTTPServer(("127.0.0.1", 8001), Handler).serve_forever()
```

**Step 2: Save this as** `page.html`

```html
<!doctype html>
<meta charset="utf-8">
<title>CORS lab</title>
<pre id="out">waiting...</pre>
<script>
fetch("http://127.0.0.1:8001/")
  .then(r => r.text())
  .then(t => { document.getElementById("out").textContent = "Read OK: " + t; })
  .catch(e => { document.getElementById("out").textContent = "Blocked: " + e; });
</script>
```

**Step 3: Start both servers in separate terminals**

```bash
python3 api_server.py
python3 -m http.server 8000 --bind 127.0.0.1
```

**Step 4: Ask the API with curl**

```bash
curl -si -H "Origin: http://127.0.0.1:8000" http://127.0.0.1:8001/
```

You should get `HTTP/1.0 200 OK` and the JSON body. There is no `Access-Control-Allow-Origin` header, and curl does not care.

**Step 5: Ask the API from the browser**

Open `http://127.0.0.1:8000/page.html`, then open the developer tools console (usually F12).

The page should say `Blocked: TypeError: Failed to fetch`, and the console should show a CORS error. Exact wording varies by browser.

**Step 6: Give permission and try again**

Stop `api_server.py` with Ctrl+C and restart it with the allow flag:

```bash
python3 api_server.py --allow
```

Reload the page. It should now say `Read OK` followed by the JSON (JavaScript Object Notation) message.

Run the curl command from step 4 again and notice the new header in the response.

**Questions to answer**

1. In step 4, did the server refuse to talk to curl? What does that tell you about who enforces CORS?
2. In step 5, did the request fail, or was the response blocked? Where would you look to find out?
3. Why does the allow flag name one exact origin instead of `*`?

Stop both servers with Ctrl+C when you are done.

---

## Key Takeaway

The same-origin policy keeps one website from reading another site's data through your browser. CORS is how a server deliberately lets specific origins through.

It is a browser rule, not a server defense. Authenticate and authorize every request as though CORS did not exist.

---

## Verified References

- MDN Web Docs, Same-origin policy. <https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy>
- MDN Web Docs, Cross-Origin Resource Sharing (CORS). <https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS>
- OWASP CORS Security Cheat Sheet. <https://cheatsheetseries.owasp.org/cheatsheets/CORS_Security_Cheat_Sheet.html>
- IETF RFC 6454, The Web Origin Concept. <https://www.rfc-editor.org/rfc/rfc6454>
- WHATWG Fetch Standard (defines the CORS protocol). <https://fetch.spec.whatwg.org/>
