Skip to main content

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

Updated 7 min readMarkdown
Part of seriesZero Trust Threads Foundations
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:

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, 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:

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.


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.

"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 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

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

<!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

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

Step 4: Ask the API with curl

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:

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

About the author

  • Zero Trust Threads is a cybersecurity media and lifestyle brand focused on making cybersecurity, Linux, networking, GRC, and tech culture approachable through practical projects, real-world learning, and a little humor. Trust nothing. Learn everything.

No comments yet. Be the first to comment.

Zero Trust Threads Foundations

Part 28 of 30

Cybersecurity does not have to be learned all at once. Zero Trust Threads Foundations breaks down essential cybersecurity and IT concepts into approachable, practical lessons for beginners. Learn the fundamentals of HTTP security, home labs, Linux, logs, defensive security, and more while building the knowledge needed for hands-on learning.

Up nextHTTP Methods and Status Codes: Reading the Web's ConversationYou open a web server's access log and see this line: 127.0.0.1 - - [30/Nov/2026 13:53:52] "GET /admin HTTP/1.1" 403 - Seven words in quotes and one number. That line already tells a small story, and