Part 03 · The Language of the Web

CORS: Why Browsers Say No

CORSBrowser

Why a browser blocks some cross-origin calls, and how a server grants permission.

⏱ 1-2 hours · Station 35 of 153

It works in Postman, so why not in the browser?

You build an API at https://api.shop.com and a frontend at https://app.shop.com. Every request works in curl and Postman. Then the frontend calls it with fetch, and the console turns red:

Access to fetch at 'https://api.shop.com/cart' from origin 'https://app.shop.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.

Nothing is wrong with your API. curl and Postman are just programs sending bytes; they don't care who asked. The browser is different. It runs code from thousands of websites, and every one of them could try to use your logged-in cookies to read your bank, your email or your company dashboard. So the browser keeps a strict rule: a page may only read responses from its own origin, unless the other server says "yes, that page is allowed".

That "yes" is CORS, Cross-Origin Resource Sharing. It's a set of HTTP headers the server sends, and a set of rules the browser follows. Once you see that the server gives permission and the browser enforces it, the red console errors become easy to fix, and you'll stop "fixing" them in ways that open security holes.

The problem: the browser holds your keys

When you're logged in to bank.com, your browser holds its session cookie. Now you open evil.example in another tab. Its JavaScript can try:

fetch("https://bank.com/api/balance", { credentials: "include" })

The browser would attach your bank cookie automatically (lesson 6). If the page could then read the response, any website you visit could read your balance, your messages and your private data.

Who sends the requestHas your cookies?Who decides if the response can be read
curl, Postman, a backend serviceno (only what you give it)nobody, the program just reads it
A page on the same originyesnobody, same origin is trusted
A page on another originyes, the browser attaches themthe server via CORS headers, enforced by the browser

The same-origin policy is the default "no". CORS is the controlled way for a server to say "yes" to specific other origins.

Think of a school gate

A school gatekeeper lets parents pick up children. A stranger walks up and says "I'm here for Rafi".

  • The gatekeeper doesn't decide on their own. They check the list the parents gave the school: who is allowed to collect this child.
  • If the stranger is on the list, the child goes with them. If not, the child stays inside.
  • The gatekeeper protects the child (your data in the response). It doesn't stop strangers from walking up to the gate and talking (the request still arrives).

The browser is the gatekeeper, the server writes the list (CORS headers), and the response is the child.

trusted page: app.shop.comapp.shop.compage JSbrowserchecks CORSapi.shop.comDELETE?OPTIONSallow appDELETE200preflight said yes, so the DELETE went out and JS reads 200stranger's page: evil.exampleevil.examplepage JSbrowserchecks CORSapi.shop.comDELETE?OPTIONSno allowno Access-Control-Allow-Origin: the DELETE never leaves the browser
On top, a page from app.shop.com asks the browser to send a DELETE. The browser first sends an OPTIONS request to api.shop.com, gets back "allow app", then sends the DELETE and hands the 200 response to the page's JavaScript. Below, a page from evil.example asks for the same DELETE. The OPTIONS answer has no allow header, so the browser stops and the DELETE never leaves.

Where the analogy stops working. A gatekeeper stops the stranger before anything happens. For "simple" requests, the browser sends the request first and only hides the response afterwards. The server still runs the handler. That's why CORS is not protection for your server, only for your users' data.

The building blocks

  1. Origin = scheme + host + port. https://app.shop.com and https://api.shop.com are different origins (different host). So are http://shop.com and https://shop.com (different scheme), and localhost:3000 and localhost:8080 (different port). The path doesn't matter.
  2. The browser sends Origin. On a cross-origin request, the browser adds Origin: https://app.shop.com. The page can't fake it; JavaScript isn't allowed to set this header.
  3. The server answers with Access-Control-Allow-Origin. Either the exact origin (https://app.shop.com) or * (anyone). If it's missing or doesn't match, the browser blocks JavaScript from reading the response.
  4. Simple requests go straight out. GET, HEAD or POST with only basic headers (no Authorization, and Content-Type only text/plain, form data or multipart) are sent immediately. These are the same requests an HTML form could always send, so CORS adds no new risk by allowing them out.
  5. Everything else gets a preflight. PUT, DELETE, PATCH, a JSON Content-Type or an Authorization header: the browser first sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers. Only if the answer allows that origin, method and headers does the real request go out.
  6. Preflight results are cached. Access-Control-Max-Age: 600 lets the browser skip the preflight for that URL for 10 minutes. Without it, every non-simple call costs an extra round trip.
  7. Cookies need extra permission. With credentials: "include", the server must reply with the exact origin (not *) and Access-Control-Allow-Credentials: true. A wildcard with credentials is always rejected, so a public * API can never be read with a user's cookies.
  8. Vary: Origin. If the response changes with the Origin header, say so, or a cache or CDN may give one origin's CORS headers to another.
Predict first

A page on https://evil.example runs fetch('https://api.shop.com/cart', { credentials: 'include' }) with a simple GET. api.shop.com sends no CORS headers. What happens on the server?

Behind the scenes: a DELETE from another origin

Step through it

The frontend deletes a cart item

Page JSBrowserAPI server

Step 1/5 The page calls fetch

JavaScript on https://app.shop.com calls fetch('https://api.shop.com/cart/7', { method: 'DELETE', headers: { Authorization: 'Bearer t1' } }).

origin
https://app.shop.com
method
DELETE

The picture to keep in your head

CORS is a permission slip written by the server and checked by the browser.

  • Server writes it: Access-Control-Allow-Origin and friends, per origin.
  • Browser checks it: before handing a response to JavaScript, and before sending risky requests (preflight).
  • Non-browser clients ignore it: curl, mobile apps and other servers never look at the slip.
  • It protects users' data, not your server: authentication, authorization and CSRF defences still have to live on the server.

Try it: will the browser allow it?

Try each case

Allowed or blocked?

no CORS headers needed
works: Same scheme, host and port. The same-origin policy allows it; CORS doesn't even apply.

Code from first principles

A small API server with a CORS policy (it trusts only https://app.shop.com, and /public is open to everyone without cookies), plus a tiny "browser" that follows the CORS rules: simple requests go straight out, others get a preflight, and the response is handed to the page only if the headers allow it. The server logs every request that reaches it, so you can see what CORS does and doesn't stop.

package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"strings"
)

const api = "https://api.shop.com" // the server's own origin
var allowed = map[string]bool{"https://app.shop.com": true}
var seen []string // every request that reached the server

type resp struct {
	status  int
	headers map[string]string
	body    string
}

// parseHead reads a request or response head and returns its first line and lower-cased headers.
func parseHead(r *bufio.Reader) (string, map[string]string) {
	first, _ := r.ReadString('\n')
	h := map[string]string{}
	for {
		line, err := r.ReadString('\n')
		if err != nil || line == "\r\n" {
			break
		}
		k, v, _ := strings.Cut(strings.TrimRight(line, "\r\n"), ": ")
		h[strings.ToLower(k)] = v
	}
	return strings.TrimSpace(first), h
}

// The API server and its CORS policy.
func handle(conn net.Conn) {
	defer conn.Close()
	line, h := parseHead(bufio.NewReader(conn))
	parts := strings.Fields(line)
	method, path := parts[0], parts[1]
	seen = append(seen, method+" "+path)
	origin := h["origin"]
	out := map[string]string{}
	status, body := 200, ""
	switch {
	case method == "OPTIONS": // preflight: say what's allowed, only to origins we trust
		status = 204
		if allowed[origin] {
			out["Access-Control-Allow-Origin"] = origin
			out["Access-Control-Allow-Methods"] = "GET, POST, DELETE"
			out["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
			out["Access-Control-Max-Age"] = "600"
		}
	case path == "/public": // public data: any site may read it, but not with cookies
		out["Access-Control-Allow-Origin"] = "*"
		body = `{"news":"sale"}`
	default:
		if allowed[origin] {
			out["Access-Control-Allow-Origin"] = origin
			out["Access-Control-Allow-Credentials"] = "true"
		}
		if method == "DELETE" {
			body = `{"deleted":7}`
		} else {
			body = `{"items":2}`
		}
	}
	reason := map[int]string{200: "OK", 204: "No Content"}[status]
	fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nVary: Origin\r\n", status, reason, len(body))
	for _, k := range []string{"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
		"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"} {
		if v, ok := out[k]; ok {
			fmt.Fprintf(conn, "%s: %s\r\n", k, v)
		}
	}
	fmt.Fprintf(conn, "Connection: close\r\n\r\n%s", body)
}

func send(method, path string, headers [][2]string) resp {
	conn, _ := net.Dial("tcp", "127.0.0.1:8097")
	defer conn.Close()
	req := method + " " + path + " HTTP/1.1\r\nHost: api.shop.com\r\n"
	for _, kv := range headers {
		req += kv[0] + ": " + kv[1] + "\r\n"
	}
	io.WriteString(conn, req+"Connection: close\r\n\r\n")
	r := bufio.NewReader(conn)
	first, h := parseHead(r)
	var status int
	fmt.Sscanf(first, "HTTP/1.1 %d", &status)
	body, _ := io.ReadAll(r)
	return resp{status, h, string(body)}
}

// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
func fetch(page, method, path, auth string, cookies bool) string {
	extra := ""
	if cookies {
		extra = " +cookies"
	}
	label := fmt.Sprintf("%s %s from %s%s", method, path, page, extra)
	var hs [][2]string
	if cookies {
		hs = append(hs, [2]string{"Cookie", "session=abc"})
	}
	if auth != "" {
		hs = append(hs, [2]string{"Authorization", auth})
	}
	if page == api { // same origin: no CORS check at all
		r := send(method, path, hs)
		return fmt.Sprintf("%s (same origin): %d, JS reads %s", label, r.status, r.body)
	}
	pre := ""
	simple := (method == "GET" || method == "HEAD" || method == "POST") && auth == ""
	if !simple { // ask permission first
		p := send("OPTIONS", path, [][2]string{{"Origin", page},
			{"Access-Control-Request-Method", method}, {"Access-Control-Request-Headers", "authorization"}})
		ok := p.headers["access-control-allow-origin"] == page &&
			strings.Contains(p.headers["access-control-allow-methods"], method) &&
			strings.Contains(strings.ToLower(p.headers["access-control-allow-headers"]), "authorization")
		if !ok {
			return fmt.Sprintf("%s: preflight failed, %s never sent", label, method)
		}
		pre = "preflight ok, "
	}
	r := send(method, path, append([][2]string{{"Origin", page}}, hs...))
	acao := r.headers["access-control-allow-origin"]
	blocked := ""
	switch {
	case acao == "":
		blocked = "no Access-Control-Allow-Origin"
	case acao == "*" && cookies:
		blocked = "wildcard * not allowed with cookies"
	case acao != "*" && acao != page:
		blocked = "origin does not match"
	case cookies && r.headers["access-control-allow-credentials"] != "true":
		blocked = "credentials not allowed"
	}
	if blocked != "" {
		return fmt.Sprintf("%s: %s%d, blocked: %s", label, pre, r.status, blocked)
	}
	return fmt.Sprintf("%s: %s%d, JS reads %s", label, pre, r.status, r.body)
}

func main() {
	ln, _ := net.Listen("tcp", "127.0.0.1:8097")
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				return
			}
			handle(c)
		}
	}()
	app, evil := "https://app.shop.com", "https://evil.example"
	lines := []string{
		fetch(api, "GET", "/cart", "", true),
		fetch(app, "GET", "/cart", "", true),
		fetch(evil, "GET", "/cart", "", true),
		fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
		fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
		fetch(evil, "GET", "/public", "", false),
		fetch(app, "GET", "/public", "", true),
	}
	for i, l := range lines {
		fmt.Printf("%d. %s\n", i+1, l)
	}
	fmt.Printf("server saw %d requests: %s\n", len(seen), strings.Join(seen, ", "))
}

Output (the same in all five languages):

1. GET /cart from https://api.shop.com +cookies (same origin): 200, JS reads {"items":2}
2. GET /cart from https://app.shop.com +cookies: 200, JS reads {"items":2}
3. GET /cart from https://evil.example +cookies: 200, blocked: no Access-Control-Allow-Origin
4. DELETE /cart/7 from https://app.shop.com: preflight ok, 200, JS reads {"deleted":7}
5. DELETE /cart/7 from https://evil.example: preflight failed, DELETE never sent
6. GET /public from https://evil.example: 200, JS reads {"news":"sale"}
7. GET /public from https://app.shop.com +cookies: 200, blocked: wildcard * not allowed with cookies
server saw 8 requests: GET /cart, GET /cart, GET /cart, OPTIONS /cart/7, DELETE /cart/7, OPTIONS /cart/7, GET /public, GET /public

Reading the output:

  • Line 1, same origin: no CORS check. The page reads the cart.
  • Line 2, trusted origin with cookies: the server echoed https://app.shop.com and Allow-Credentials: true, so JavaScript reads it.
  • Line 3 is the important one. evil.example's GET got a 200: the server ran the handler with the user's cookie. The browser only stopped the page from reading it. Look at the last line: the server saw three GET /cart requests, including evil's.
  • Lines 4 and 5, DELETE: the trusted page got preflight ok and then the DELETE. For evil.example the preflight answer had no allow header, so the DELETE never left the browser. The server log shows only OPTIONS /cart/7 for it, no second DELETE.
  • Line 6: /public sends *, so even evil.example may read it without cookies.
  • Line 7: the same * with cookies is blocked, even for the trusted origin. Wildcards and credentials never mix.

And a real API, GitHub, answering a preflight from a made-up origin:

$ curl -s -o /dev/null -D - -X OPTIONS https://api.github.com/user -H "Origin: https://evil.example" -H "Access-Control-Request-Method: DELETE" -H "Access-Control-Request-Headers: authorization" | grep -iE "^(HTTP|access-control-allow-(origin|methods)|access-control-max-age)"
HTTP/2 204
access-control-max-age: 86400
access-control-allow-methods: GET, POST, PATCH, PUT, DELETE
access-control-allow-origin: *
$ curl -s -o /dev/null -D - https://www.google.com/ -H "Origin: https://evil.example" | grep -ciE "^access-control"
0
  • 204 with allow-origin: *: GitHub's API lets any website call it. That's safe for them because the API is authenticated with tokens in the Authorization header, not cookies, and * can never be combined with cookies.
  • max-age: 86400: browsers may cache this preflight for up to a day (Chrome caps it at 2 hours).
  • google.com's home page sends 0 CORS headers: it's an HTML page, not an API, so no other site may read it with fetch.

Real engineering

  • Keep an explicit allowlist of origins, per environment: https://app.shop.com in production, http://localhost:3000 only in development. Compare exact strings.
  • Use your framework's CORS middleware (Go rs/cors, Express cors, Spring @CrossOrigin/CorsConfiguration, FastAPI CORSMiddleware) instead of hand-writing headers, and configure it rather than turning on "allow all".
  • Answer OPTIONS before auth. Preflights carry no cookies or tokens. If your auth middleware rejects them with 401, every non-simple request fails.
  • Set Access-Control-Max-Age to cut preflight round trips, and send Vary: Origin when the allowed origin depends on the request.
  • Expose the headers the frontend needs. By default JavaScript can read only a few response headers. Use Access-Control-Expose-Headers: ETag, Location, X-Request-Id for the rest.
  • Avoid CORS entirely when you can: serve the frontend and API from the same origin (shop.com and shop.com/api) through a reverse proxy. No preflights, no configuration, cookies just work.
  • CORS is not CSRF protection. Simple cross-origin POSTs still reach your server with cookies. Use SameSite cookies, CSRF tokens or require a JSON content type for state-changing requests.

When it breaks

Try each case

Pick a failure

No 'Access-Control-Allow-Origin' header is present
breaks: The API doesn't send CORS headers for this origin. Add the frontend's origin to the allowlist on the server. A browser extension that disables CORS only hides the problem on your machine.

Think before you read on

If CORS doesn't stop the server from receiving a simple cross-origin POST, why do browsers bother with preflights for DELETE and JSON requests at all?

Reveal

Because of what was already possible before CORS existed. An HTML <form> on any website could always POST to any other site, with cookies, using form encoding. Servers had to defend against that anyway (CSRF). So letting fetch send the same kinds of requests adds no new danger. But no old web page could send a DELETE, a JSON body or a custom Authorization header to another site. Many servers were written assuming those only come from their own pages. The preflight protects those servers: it asks first, and older servers that know nothing about CORS answer without the allow headers, so the risky request is never sent.

Check yourself

1. What makes two URLs the same origin?

Answer

The same scheme, host and port. https://shop.com/a and https://shop.com/b are the same origin; https://shop.com and https://api.shop.com are not.

2. Who enforces CORS: the server or the browser?

Answer

The browser. The server only sends headers saying which origins, methods and headers it allows. curl, mobile apps and other servers ignore them.

3. Which requests trigger a preflight?

Answer

Anything that isn't a simple request: methods other than GET, HEAD and POST, custom headers such as Authorization, or a Content-Type other than text/plain, form data or multipart (for example application/json).

4. Why can't you use Access-Control-Allow-Origin: * with cookies?

Answer

Because that would let every website read responses made with the user's cookies. With credentials, the browser requires the exact origin and Access-Control-Allow-Credentials: true.

Your challenge: add a preflight cache

Extend the tiny browser in the code:

  • Keep a preflight cache keyed by (origin, method, path). When a preflight succeeds, store it with an expiry from Access-Control-Max-Age, using a fake clock you advance by hand.
  • Before preflighting, check the cache; skip the OPTIONS request if there's a fresh entry.
  • From https://app.shop.com, send DELETE /cart/7 three times, advance the clock by 700 seconds, and send it once more.

Before you run it, predict how many OPTIONS requests the server will see.

You've succeeded when the server log shows 2 OPTIONS /cart/7 and 4 DELETE /cart/7, and changing the server's Max-Age to 0 makes it 4 and 4.

The mental model

The same-origin policy stops a page from reading another origin's responses, because the browser carries the user's cookies everywhere. CORS lets a server grant exceptions with headers: Allow-Origin, Allow-Methods, Allow-Headers, Allow-Credentials. The browser enforces them, sending simple requests straight away and preflighting the rest with OPTIONS. Use an exact allowlist, answer preflights before auth, never pair * with credentials, and remember that CORS protects users' data in the browser, not your server.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →