CORS and Security Basics
Let a React app on another port call your API. See why the browser blocks it, what a preflight request is, and how CORSMiddleware answers it - tested in a real browser. Then three real traps: an origin that never matches, "*" with credentials that lets ANY site in, and a 500 error that the browser reports as a CORS error. Plus three security headers for every response.
What you will be able to do
- Explain what an origin is, and when two URLs have different origins
- Explain why a browser blocks a page from reading another origin’s answer
- Tell a simple request from one that needs a preflight
- Set up CORSMiddleware for one frontend, with only the methods and headers it needs
- Know that CORS does not protect your API - your login does
- Avoid the "*" with credentials trap and the 500-that-looks-like-CORS trap
- Add a few security headers to every response
The idea, in plain English
Your React app runs on http://localhost:5173. Your API runs on http://localhost:8000. Different port, so to the browser they are two different "origins" - two different websites. By default, a browser does not let a page read answers from another origin. This rule protects users: a bad website cannot read your bank page with your cookies.
CORS (Cross-Origin Resource Sharing) is how your API tells the browser "this other origin may read my answers". It is just a few response headers, like Access-Control-Allow-Origin. For some requests the browser first asks with an OPTIONS request - a "preflight" - before it sends the real one. FastAPI’s CORSMiddleware writes these headers and answers the preflights for you.
We take the to-do API from Lesson 6.4, call it from a page on port 5173 in a real browser (headless Chromium 159, driven by Playwright 1.65.2), and count every request in the server log. FastAPI 0.143.0 (Starlette 1.10.0), SQLModel 0.0.50, PyJWT 2.15.1, pwdlib 0.3.1.
Worked example: The to-do API from Lesson 6.4, called by a React app on http://localhost:5173: blocked at first, then allowed for exactly that one origin - with ravi logging in, listing and deleting todos from a real browser.
1 - No CORS setup
The login reached the API and ran - but the browser hid the answer. The GET with a token needed a preflight, and the API said 405.
The browser sits between the React app and the API, and decides what the page may read. Real results from our test.
Words you will see in this lesson
A few new words. They all come from how browsers work.
OriginScheme + host + port of a page, like http://localhost:5173. The path does not count.Same-origin policyThe browser rule: a page may not read answers from another origin, unless that origin allows it.CORSCross-Origin Resource Sharing - response headers that say which other origins may read the answer.PreflightAn OPTIONS request the browser sends first, to ask "may I send this request?".Simple requestA plain GET or POST (for example a form) - the browser sends it at once, with no preflight.CredentialsCookies (and HTTP login) that the browser adds to a request by itself.Security headerA response header that tells the browser to be more careful, like X-Frame-Options.An everyday example: a careful assistant
- You work at shop A. You ask your assistant (the browser) to fetch a letter from bank B.
- The assistant goes to the bank and gets the letter. Then, before giving it to you, the assistant looks for a note from the bank: "shop A may read this". No note - the letter goes in the bin.
- For unusual errands (a DELETE, a request with a special header), the assistant phones the bank FIRST and asks "may shop A do this?". That phone call is the preflight.
- Someone without an assistant (curl, a Python script) walks into the bank directly. The note means nothing to them - only the bank’s own ID check (your login) stops them.
What counts as the same origin?
Compare everything with http://localhost:5173, where the React app runs:
http://localhost:5173/todosSame origin - only the path is different.http://localhost:8000Different - another port. This is our API.http://127.0.0.1:5173Different - another host name, even if it is the same machine.https://localhost:5173Different - another scheme (https).Tip: In production you can often avoid CORS: serve the React app and the API from ONE origin, for example https://todo.example.com and https://todo.example.com/api, through a proxy (Lesson 10.3). Same origin - no CORS needed.
Example 1 - the React app calls the API
The React app keeps its API calls in api.js. These are the same fetch calls a React component makes. To test without a build step, we loaded api.js into a plain page served on port 5173, and drove it with Playwright:
- login() sends ravi’s username and password as a form to POST /token (Lesson 6.3).
- getTodos() and deleteTodo() send the token in an Authorization: Bearer header (Lesson 6.4).
- browser.py opens the page in headless Chromium, logs in, calls GET /todos three times and DELETE /todos/1, and prints the browser’s console errors.
- The API is todos.py from Lesson 6.4, unchanged. We read the server log to see what really reached it.
const API = "http://localhost:8000";
export async function login(username, password) {
const r = await fetch(API + "/token", {
method: "POST",
body: new URLSearchParams({ username, password }), // a form, like OAuth2PasswordRequestForm wants
});
if (!r.ok) throw new Error("login failed: " + r.status);
return (await r.json()).access_token;
}
export async function getTodos(token) {
const r = await fetch(API + "/todos", {
headers: { Authorization: "Bearer " + token },
});
if (!r.ok) throw new Error("GET /todos: " + r.status);
return r.json();
}
export async function deleteTodo(token, id) {
const r = await fetch(API + "/todos/" + id, {
method: "DELETE",
headers: { Authorization: "Bearer " + token },
});
return r.status;
}import sys
from playwright.sync_api import sync_playwright
page_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:5173"
STEPS = """async () => {
const out = [];
let token = null;
try { token = await api.login("ravi", "ravi-pass-2026"); out.push("login -> got a token"); }
catch (e) { out.push("login -> " + e); }
for (let i = 1; i <= 3; i++) {
try { out.push("GET /todos -> " + JSON.stringify(await api.getTodos(token))); }
catch (e) { out.push("GET /todos -> " + e); }
}
try { out.push("DELETE /todos/1 -> " + await api.deleteTodo(token, 1)); }
catch (e) { out.push("DELETE /todos/1 -> " + e); }
return out;
}"""
STATS = """async () => {
const token = await api.login("ravi", "ravi-pass-2026");
try { return ["GET /stats -> " + JSON.stringify(await api.getStats(token))]; }
catch (e) { return ["GET /stats -> " + e]; }
}"""
steps = STATS if len(sys.argv) > 2 and sys.argv[2] == "stats" else STEPS
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
console = []
page.on("console", lambda m: console.append(m.text) if m.type == "error" else None)
page.goto(page_url)
page.wait_for_function("window.ready")
print("page:", page_url)
for line in page.evaluate(steps):
print(" ", line)
print("browser console errors:", len(console))
for text in console:
print(" !", text)
browser.close()page: http://localhost:5173
login -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
DELETE /todos/1 -> TypeError: Failed to fetch
browser console errors: 10
! Access to fetch at 'http://localhost:8000/token' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
! Access to fetch at 'http://localhost:8000/todos' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
--- server log
127.0.0.1:53396 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:53396 - "OPTIONS /todos HTTP/1.1" 405 Method Not Allowed
127.0.0.1:53396 - "OPTIONS /todos HTTP/1.1" 405 Method Not Allowed
127.0.0.1:53408 - "OPTIONS /todos HTTP/1.1" 405 Method Not Allowed
127.0.0.1:53408 - "OPTIONS /todos/1 HTTP/1.1" 405 Method Not AllowedReading the output
- In the page, every call failed with "TypeError: Failed to fetch". The browser does not tell your JavaScript WHY - the reason is only in the console (10 errors).
- Look at the server log: POST /token 200. The login reached the API and ran. The browser received the token - and then threw it away, because there was no Access-Control-Allow-Origin header.
- So the browser does NOT stop a simple request from reaching the server. It only stops the page from reading the answer.
- GET /todos never reached the API. It has an Authorization header, so the browser first sent OPTIONS /todos - a preflight. FastAPI has no OPTIONS route, so it said 405, and the real GET was never sent.
- Same for DELETE /todos/1: OPTIONS /todos/1, 405, nothing deleted.
The fix: CORSMiddleware
Add one middleware to todos.py, right after the app is made:
- allow_origins - the exact origins that may read your answers. Scheme + host + port, as the browser writes them.
- allow_methods - the methods a preflight may ask for. The default is only GET.
- allow_headers - the extra headers a preflight may ask for. We need Authorization (the token) and Content-Type (JSON bodies). The default is none.
- We do not set allow_credentials. Our token travels in a header that our own JavaScript adds, not in a cookie, so we do not need it.
- Middleware is code that runs around every request. Lesson 7.4 explains it; here you only need add_middleware.
from fastapi.middleware.cors import CORSMiddleware # one new import
# ... everything from Lesson 6.4 stays the same ...
app = FastAPI(lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"], # your React app: scheme + host + port, no "/" at the end
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)page: http://localhost:5173
login -> got a token
GET /todos -> [{"id":1,"title":"Buy milk"}]
GET /todos -> [{"id":1,"title":"Buy milk"}]
GET /todos -> [{"id":1,"title":"Buy milk"}]
DELETE /todos/1 -> 204
browser console errors: 0
--- server log
127.0.0.1:53420 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:53420 - "OPTIONS /todos HTTP/1.1" 200 OK
127.0.0.1:53420 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:53420 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:53420 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:53420 - "OPTIONS /todos/1 HTTP/1.1" 200 OK
127.0.0.1:53436 - "DELETE /todos/1 HTTP/1.1" 204 No ContentReading the output again
- Everything works: a token, ravi’s "Buy milk", and 204 for the delete. 0 console errors.
- POST /token had no preflight. A form body and no special headers make it a simple request.
- OPTIONS /todos came once, then three GETs. The browser remembered the answer - Access-Control-Max-Age is 600 seconds by default in Starlette.
- DELETE /todos/1 needed its own preflight (OPTIONS /todos/1). The browser remembers preflights per URL, so every new URL is asked again.
Simple request or preflight?
The browser decides, not you. From our own log:
POST /token with a formNo preflight - a simple request. The server ran it even when the browser hid the answer.GET /todos with AuthorizationPreflight - Authorization is not a "simple" header.DELETE /todos/1Preflight - DELETE is not GET, HEAD or POST.POST with Content-Type: application/jsonPreflight too - only form and plain text bodies are simple.Watch out: A simple request runs on your server even when CORS says no. So never let a simple GET or form POST change data without a login check - the CORS headers will not stop it.
What the API answers to each caller
cors_check.py plays the browser: it sends the same Origin and preflight headers, and prints Access-Control-Allow-Origin:
- The preflight from React - 200 "OK" and allow-origin=http://localhost:5173.
- From 127.0.0.1:5173 - 400 "Disallowed CORS origin". A PUT (not in allow_methods) - "Disallowed CORS method". An X-Request-Id header (not in allow_headers) - "Disallowed CORS headers".
- GET from React without a token - 401, WITH the CORS header. Good: React can read the 401 and send ravi to the login page.
- GET from evil.example with ravi’s token - 200 and the data! No CORS header, so a browser would hide it. But anything that is not a browser gets it.
from fastapi.testclient import TestClient
from todos import app
REACT = "http://localhost:5173"
def preflight(c, origin, method="GET", headers="authorization"):
return c.options("/todos", headers={
"Origin": origin,
"Access-Control-Request-Method": method, # "may I send a GET...
"Access-Control-Request-Headers": headers, # ...with an Authorization header?"
})
def show(label, r):
allow = r.headers.get("access-control-allow-origin", "-")
print(f"{label:<34} -> {r.status_code} allow-origin={allow:<22} {r.text[:40]}")
with TestClient(app) as c:
token = c.post("/token", data={"username": "ravi", "password": "ravi-pass-2026"}).json()["access_token"]
bearer = {"Authorization": f"Bearer {token}"}
show("preflight from React", preflight(c, REACT))
show("preflight from 127.0.0.1:5173", preflight(c, "http://127.0.0.1:5173"))
show("preflight for PUT", preflight(c, REACT, method="PUT"))
show("preflight with X-Request-Id", preflight(c, REACT, headers="authorization,x-request-id"))
show("GET from React", c.get("/todos", headers={"Origin": REACT, **bearer}))
show("GET from React, no token", c.get("/todos", headers={"Origin": REACT}))
show("GET from evil.example", c.get("/todos", headers={"Origin": "https://evil.example", **bearer}))preflight from React -> 200 allow-origin=http://localhost:5173 OK
preflight from 127.0.0.1:5173 -> 400 allow-origin=- Disallowed CORS origin
preflight for PUT -> 400 allow-origin=http://localhost:5173 Disallowed CORS method
preflight with X-Request-Id -> 400 allow-origin=http://localhost:5173 Disallowed CORS headers
GET from React -> 200 allow-origin=http://localhost:5173 [{"id":1,"title":"Buy milk"}]
GET from React, no token -> 401 allow-origin=http://localhost:5173 {"detail":"Not authenticated"}
GET from evil.example -> 200 allow-origin=- [{"id":1,"title":"Buy milk"}]CORS is not a lock on your API
The same two requests with curl:
- The preflight answer lists everything the browser may do: the methods, the headers (Starlette always adds the four simple ones, like Accept), the origin, and max-age 600.
- curl with Origin: https://evil.example and a token - 200 and the todos. curl has no same-origin policy.
- CORS protects USERS of a browser: another website cannot read your API’s answers through their browser.
- Your DATA is protected by the login and the checks from Lesson 6.4. Without a token, everyone gets 401 - with or without CORS.
$ curl -i -X OPTIONS http://localhost:8000/todos -H "Origin: http://localhost:5173" \
-H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: authorization"
HTTP/1.1 200 OK
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network
access-control-allow-methods: GET, POST, PATCH, DELETE
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type
access-control-allow-origin: http://localhost:5173
content-type: text/plain; charset=utf-8
OK
$ curl -i http://localhost:8000/todos -H "Origin: https://evil.example" -H "Authorization: Bearer $TOKEN"
HTTP/1.1 200 OK
content-type: application/json
vary: Origin
[{"id":1,"title":"Buy milk"}]Counting preflights: max_age
A preflight is one more request before the real one. We set max_age=0 (do not remember) and ran browser.py again:
- max_age=0: three GET /todos needed three OPTIONS /todos - 9 requests to the API in total.
- Default (600): one OPTIONS /todos for three GETs - 7 requests in total.
- On a slow phone network every preflight is a full round trip. Keep the default, or set a bigger max_age; browsers have their own upper limit.
page: http://localhost:5173
login -> got a token
GET /todos -> [{"id":1,"title":"Buy milk"}]
GET /todos -> [{"id":1,"title":"Buy milk"}]
GET /todos -> [{"id":1,"title":"Buy milk"}]
DELETE /todos/1 -> 204
browser console errors: 0
--- server log
127.0.0.1:50362 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:50362 - "OPTIONS /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "OPTIONS /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "OPTIONS /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "GET /todos HTTP/1.1" 200 OK
127.0.0.1:50362 - "OPTIONS /todos/1 HTTP/1.1" 200 OK
127.0.0.1:50370 - "DELETE /todos/1 HTTP/1.1" 204 No ContentTrap 1: an origin that never matches
allow_origins is compared character by character with the Origin header. Two real mistakes from our tests:
- A slash at the end: "http://localhost:5173/". The browser sends "http://localhost:5173" - no match, no header, blocked (traps.py, below).
- Opening the app at http://127.0.0.1:5173 instead of http://localhost:5173. Another host, another origin: every preflight got 400, and the page got "Failed to fetch".
- The fix: copy the origin from the browser’s console message ("from origin '...'"), and list each one you really use.
page: http://127.0.0.1:5173
login -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
GET /todos -> TypeError: Failed to fetch
DELETE /todos/1 -> TypeError: Failed to fetch
browser console errors: 10
--- server log
127.0.0.1:50348 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:50348 - "OPTIONS /todos HTTP/1.1" 400 Bad Request
127.0.0.1:50348 - "OPTIONS /todos HTTP/1.1" 400 Bad Request
127.0.0.1:50348 - "OPTIONS /todos HTTP/1.1" 400 Bad Request
127.0.0.1:50348 - "OPTIONS /todos/1 HTTP/1.1" 400 Bad RequestTrap 2: "*" with credentials lets every site in
Many tutorials show allow_origins=["*"] with allow_credentials=True "to make it work". Our old notes even said browsers refuse "*" with credentials, so it is harmless. We tested it:
- The browser does refuse the header "*" with credentials. So Starlette quietly sends back the caller’s OWN origin instead.
- Result: https://evil.example got allow-origin=https://evil.example and credentials=true. The browser would let that site read the answer - with the user’s cookies.
- If you keep the login in a cookie (cookies are Lesson 3.4), any website your users visit could read their data from your API.
- The fix: list the exact origins. Then evil.example gets no allow-origin at all.
- With Bearer tokens in a header, like our API, you do not need allow_credentials. Leave it off.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
REACT = "http://localhost:5173"
def make_app(**cors):
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_methods=["GET"], allow_headers=["Authorization"], **cors)
@app.get("/todos")
def list_todos():
return [{"id": 1, "title": "Buy milk"}]
return app
def check(label, app, origin):
headers = {"Origin": origin}
with TestClient(app) as c:
r = c.get("/todos", headers=headers)
print(f"{label:<44} -> {r.status_code} "
f"allow-origin={r.headers.get('access-control-allow-origin', '-')} "
f"credentials={r.headers.get('access-control-allow-credentials', '-')}")
print("Trap 1: a slash at the end")
check(' allow_origins=["http://localhost:5173/"]', make_app(allow_origins=[REACT + "/"]), REACT)
check(' allow_origins=["http://localhost:5173"]', make_app(allow_origins=[REACT]), REACT)
print('Trap 2: "*" together with credentials')
star = make_app(allow_origins=["*"], allow_credentials=True)
check(" React", star, REACT)
check(" evil.example", star, "https://evil.example")
listed = make_app(allow_origins=[REACT], allow_credentials=True)
check(" listed origin only - evil.example", listed, "https://evil.example")Trap 1: a slash at the end
allow_origins=["http://localhost:5173/"] -> 200 allow-origin=- credentials=-
allow_origins=["http://localhost:5173"] -> 200 allow-origin=http://localhost:5173 credentials=-
Trap 2: "*" together with credentials
React -> 200 allow-origin=http://localhost:5173 credentials=true
evil.example -> 200 allow-origin=https://evil.example credentials=true
listed origin only - evil.example -> 200 allow-origin=- credentials=trueTrap 3: a 500 that looks like a CORS error
We added a GET /stats with a bug - it divides by zero. The React app called it:
- Before: the page got "Failed to fetch", and the console said "blocked by CORS policy". The server log said 500. You go and fix CORS - but CORS was fine.
- Why: an unhandled error is turned into a 500 by the outermost layer of the app, outside CORSMiddleware. So that 500 has no CORS header, and the browser hides it.
- The fix: a small middleware that catches the error and returns a normal 500 JSON answer. Add it BEFORE CORSMiddleware - the middleware added last is the outermost, so CORS then wraps it.
- After: the page reads 500 {"detail":"Internal server error"} and can show "Something went wrong". The traceback is still in the server log.
@app.get("/stats")
def stats(user: CurrentUser):
done, total = 0, 0
return {"percent_done": done / total * 100} # a bug: no todos -> ZeroDivisionErrorexport async function getStats(token) {
const r = await fetch(API + "/stats", {
headers: { Authorization: "Bearer " + token },
});
if (!r.ok) throw new Error("GET /stats: " + r.status + " " + (await r.text()));
return r.json();
}page: http://localhost:5173
GET /stats -> TypeError: Failed to fetch
browser console errors: 2
! Access to fetch at 'http://localhost:8000/stats' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
! Failed to load resource: net::ERR_FAILED
--- server log
127.0.0.1:37140 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:37140 - "OPTIONS /stats HTTP/1.1" 200 OK
127.0.0.1:37140 - "GET /stats HTTP/1.1" 500 Internal Server Errorapp = FastAPI(lifespan=lifespan)
@app.middleware("http") # added BEFORE CORS, so CORS wraps it
async def catch_errors(request: Request, call_next):
try:
return await call_next(request)
except Exception:
logger.exception("Unhandled error on %s %s", request.method, request.url.path)
return JSONResponse({"detail": "Internal server error"}, status_code=500)
app.add_middleware(
CORSMiddleware,
# ... as before ...
)page: http://localhost:5173
GET /stats -> Error: GET /stats: 500 {"detail":"Internal server error"}
browser console errors: 1
! Failed to load resource: the server responded with a status of 500 (Internal Server Error)
--- server log
127.0.0.1:37156 - "POST /token HTTP/1.1" 200 OK
127.0.0.1:37156 - "OPTIONS /stats HTTP/1.1" 200 OK
127.0.0.1:37156 - "GET /stats HTTP/1.1" 500 Internal Server ErrorWatch out: We first tried @app.exception_handler(Exception). It did NOT help: the answer was 500 {"detail":"Internal server error"} but still with allow-origin = -. A handler for Exception runs in that same outermost layer, outside CORS.
Security basics: three headers for every response
CORS says who may READ your answers. A few more headers tell the browser to be careful with them. Add them after CORSMiddleware, so they are on every answer, preflights included:
- X-Content-Type-Options: nosniff - the browser must trust your Content-Type and not guess. A JSON answer is never run as a script.
- X-Frame-Options: DENY - no other site may show your pages (like /docs) inside a frame, to trick users into clicking.
- Referrer-Policy: no-referrer - when a user leaves your page, the next site does not see your URL.
- Strict-Transport-Security (always use HTTPS) belongs on HTTPS only - Lesson 10.3.
@app.middleware("http")
async def security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff" # do not guess the file type
response.headers["X-Frame-Options"] = "DENY" # no showing us inside another site's frame
response.headers["Referrer-Policy"] = "no-referrer" # do not leak our URLs to other sites
return response$ curl -i http://localhost:8000/todos -H "Origin: http://localhost:5173" -H "Authorization: Bearer $TOKEN"
HTTP/1.1 200 OK
content-type: application/json
access-control-allow-origin: http://localhost:5173
vary: Origin
x-content-type-options: nosniff
x-frame-options: DENY
referrer-policy: no-referrer
[{"id":1,"title":"Buy milk"}]A security checklist for Module 6
What you have now, and what is still to come:
PasswordsHashed with Argon2, never stored as text.TokensShort access tokens, signed with a long random key.Every requestThe user is loaded from the database; owners and roles checked.BrowsersCORS for your exact frontend origins; never "*" with credentials.ErrorsA clean 500 JSON answer; details only in the server log.SecretsThe secret key and origins from environment variables.HTTPSAlways in production, behind a proxy.CORS at a glance
Allow your frontendExact origins: scheme + host + port, no slash.
app.add_middleware(CORSMiddleware, allow_origins=["http://localhost:5173"])
MethodsDefault is only GET.
allow_methods=["GET", "POST", "PATCH", "DELETE"]
HeadersNeeded for Bearer tokens and JSON bodies.
allow_headers=["Authorization", "Content-Type"]
CookiesOnly if you log in with cookies - and then never with "*".
allow_credentials=True
Preflight cacheSeconds the browser may remember a preflight. Default 600.
max_age=600
Read a header in JSOnly simple response headers are readable by default.
expose_headers=["X-Request-Id"]
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Remove app.add_middleware(CORSMiddleware, ...), start the API, and call fetch("http://localhost:8000/todos") from the console of any page on another port. Read the full error message.”
“Open your browser’s Network tab and call getTodos(token) twice, then deleteTodo(token, 1). How many OPTIONS requests do you see, and for which URLs?”
“Change allow_headers to ["Content-Type"] only and run browser.py. Which call breaks first, and what does OPTIONS /todos answer in the server log?”
“Add a createTodo(token, title) to api.js with Content-Type: application/json. Does it need a preflight? Check the server log.”
What usually goes wrong
Starlette sends back the caller’s own origin, so evil.example got allow-origin and credentials=true. List your origins.
✗ allow_origins=["*"], allow_credentials=True✓ allow_origins=["http://localhost:5173", "https://todo.example.com"]The browser never sends a path, so "http://localhost:5173/" never matches.
✗ allow_origins=["http://localhost:5173/"]✓ allow_origins=["http://localhost:5173"]curl with Origin: https://evil.example got the todos. CORS only controls what a browser page may read. Protect data with login and permission checks.
The default allows no extra headers, so every request with a token fails its preflight - "Disallowed CORS headers".
✗ app.add_middleware(CORSMiddleware, allow_origins=[...])✓ app.add_middleware(CORSMiddleware, allow_origins=[...], allow_methods=[...], allow_headers=["Authorization", "Content-Type"])An unhandled error leaves the app without CORS headers. Check the server log first; catch errors in a middleware added before CORSMiddleware.
A pattern like r"https://.*\.vercel\.app" allows every app anyone puts on vercel.app - not just yours. Make the pattern match only your own names.
Best practices
- Serve frontend and API from one origin when you can - then you need no CORS at all.
- Otherwise list exact origins, one per real frontend, read from settings.
- Allow only the methods and headers your frontend sends.
- Use Bearer tokens in headers and leave allow_credentials off; with cookies, never use "*".
- Remember: simple requests still run on the server - protect them with login checks.
- Make errors return a clean 500 inside CORS, so the frontend sees the real status.
- Add nosniff, X-Frame-Options and Referrer-Policy to every response.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Read the allowed origins from an environment variable CORS_ORIGINS, like "http://localhost:5173,https://todo.example.com". Print a warning at startup if it contains "*".
Show hintHide hint
os.environ.get("CORS_ORIGINS", "http://localhost:5173").split(","), and strip spaces and slashes at the end of each origin. Lesson 8.2 does this properly with pydantic-settings.
Add an X-Request-Id header to every response (a uuid4). Make the React app able to read it with r.headers.get("X-Request-Id") - and show that it returns null before your change.
Show hintHide hint
Without expose_headers=["X-Request-Id"], the browser hides every response header that is not on its short "simple" list.
A CORS test for your API
CORS settings break quietly - a new frontend URL, a new header, a typo. Write tests that catch it before users do.
- A pytest file with TestClient that sends preflights for every method the React app uses (GET, POST, PATCH, DELETE) with Authorization and Content-Type - all 200.
- A test that a preflight from https://evil.example gets no Access-Control-Allow-Origin header.
- A test that a 401 and a 500 both carry the CORS header for the React origin.
- A test that every response has X-Content-Type-Options: nosniff.
Key points
- An origin is scheme + host + port; localhost:5173 and localhost:8000 are different origins.
- The browser, not the server, blocks a page from reading another origin’s answer.
- Requests with a token, a JSON body or a method like DELETE first send an OPTIONS preflight.
- CORSMiddleware answers preflights and adds Access-Control-Allow-Origin for listed origins.
- CORS is not a lock: curl got the data with any Origin. Your login protects the data.
- "*" with credentials made Starlette allow ANY origin, with cookies.
- An unhandled 500 had no CORS header - the browser called it a CORS error.
Quick check before you move on
Interview questions
Explain CORS and a preflight request.
Browsers block scripts from reading cross-origin responses unless the server opts in with Access-Control-Allow-Origin. For non-simple requests (methods other than GET/HEAD/POST, non-safelisted headers like Authorization, or JSON content types) the browser first sends an OPTIONS preflight with Access-Control-Request-Method/Headers; the server answers with the allowed origin, methods, headers and a max-age for caching. Simple requests are sent directly - the server processes them; only reading the response is blocked.
Is CORS a security mechanism for your API?
No - it relaxes the browser’s same-origin policy, which protects users, not servers. Non-browser clients ignore it. APIs need authentication and authorization regardless; CORS only decides which web origins may read responses in a user’s browser, which matters most when credentials such as cookies are involved.
What is wrong with allow_origins=["*"] and allow_credentials=True?
The spec forbids a wildcard with credentials, so frameworks like Starlette reflect the request Origin instead - effectively allowing every site to make credentialed requests and read the responses. With cookie-based auth this exposes user data to any website. Use an explicit allow-list (or a tight regex), and avoid credentials entirely with header-based tokens.
Quiz
- 1.
Why can curl read an answer that the browser hides?
- 2.
Why did the 401 from GET /todos have a CORS header, but the 500 from GET /stats did not?
- 3.
Our API uses Bearer tokens. Why do we not need allow_credentials=True?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...