FastAPI CORS: Blocked Preflight and Credentials Wildcard
A wildcard origin with credentials is invalid and the browser enforces it; a 500 skips the CORS middleware entirely. Both look like CORS and neither is.

Introduction & Quick Summary
Symptom. A FastAPI backend rejects a browser request with Access to fetch at 'https://api.example.com/me' from origin 'https://app.example.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include', even though CORSMiddleware is configured with allow_origins=["*"] and allow_credentials=True. Or the console reports a CORS error on an endpoint that returns 500, and the network tab shows the 500 plainly — the server never sent a CORS header on the error response.
Cause. The CORS specification forbids Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true; the browser enforces that even when the middleware is willing. Starlette historically decided the simple-response case by looking for a Cookie header on the request, which is not the same thing as a client sending credentials: "include": the first call of a session carries no cookie yet, receives *, and is blocked. And a 500 produced by ServerErrorMiddleware is generated outside CORSMiddleware, because user middleware sits inside the error middleware, so the error response has no CORS headers at all and the browser reports a CORS failure instead of the 500.
Fix. List origins explicitly, always. Add an Exception handler that attaches Access-Control-Allow-Origin to its own response, or apply the header at the proxy. Keep allow_credentials=True only when cookies are actually used, and never combine it with a wildcard.
Core Mechanics, Signatures & Reproducible Setup
The middleware only rewrites headers; the browser makes the decision, and it makes it in two phases.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com", "http://localhost:3000"],
allow_credentials=True, # required for cookie auth
allow_methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-Request-Id"],
expose_headers=["X-Request-Id"],
max_age=600, # cache the preflight for 10 minutes
)allow_origins must match the Origin header exactly: scheme, host, and port, with no trailing slash. https://app.example.com/ never matches https://app.example.com, and a null origin — a sandboxed iframe, a file:// page, some Electron shells — cannot be allowed by name at all.
Reproduce the wildcard failure in two commands:
# preflight: no cookies, so older Starlette answers with a bare *
curl -i -X OPTIONS https://api.example.com/me \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: GET" | grep -i "access-control"
# simple request
curl -i https://api.example.com/me -H "Origin: https://app.example.com" | grep -i "access-control"If the second response contains Access-Control-Allow-Origin: * next to Access-Control-Allow-Credentials: true, a browser with credentials: "include" will discard it. Newer Starlette releases echo the request origin whenever allow_credentials=True, which hides the bug on a fresh install and leaves it in place for every pinned deployment.
Key Comparison Table
| Configuration | Preflight result | Credentialed fetch | Correct for |
|---|---|---|---|
["*"], credentials off | * allowed | * allowed | public read-only APIs |
["*"], credentials on | origin echoed, new Starlette | blocked on older versions | nothing |
| explicit list, credentials on | origin echoed | allowed | cookie or bearer auth |
allow_origin_regex=".*", credentials on | origin echoed | allowed | dynamic preview hosts |
| no middleware | no headers | blocked | never |
| Mistake | Browser symptom | Fix |
|---|---|---|
| trailing slash in origin | no Allow-Origin header | strip the slash |
allow_methods missing PATCH | preflight 400 "Disallowed CORS method" | list every verb used |
| custom header not allowed | preflight 400 "Disallowed CORS headers" | add to allow_headers |
www mismatch | silent block on that host | add both origins |
| 500 bypasses middleware | CORS error, 500 in network tab | handler with explicit header |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The 500 that looks like a CORS bug
ServerErrorMiddleware is the outermost ASGI layer, so an unhandled exception produces a plain Internal Server Error before CORSMiddleware ever sees the response. The browser gets no header and reports CORS; the actual error is only in the server log.
from fastapi import Request
from fastapi.responses import JSONResponse
import logging
ALLOWED = {"https://app.example.com", "http://localhost:3000"}
@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception):
logging.exception("unhandled", exc_info=exc)
origin = request.headers.get("origin")
headers = {"Access-Control-Allow-Origin": origin} if origin in ALLOWED else {}
headers["Vary"] = "Origin"
return JSONResponse({"detail": "Internal Server Error"}, status_code=500, headers=headers)Duplicating the origin list is ugly but honest: the error path runs outside the middleware, so it has to know the same set. Read it from settings in both places.
2. HTTPException and validation errors are fine, and why
A HTTPException and a RequestValidationError are converted to responses by handlers that run inside the routing layer, so the middleware wraps them and the 422 or 404 arrives with CORS headers. Only exceptions that escape to ServerErrorMiddleware lose them. That is why raise HTTPException(400) looks fixed and raise ValueError() looks broken.
3. Cookies across sites need SameSite=None; Secure
CORS and cookie policy are separate gates, and clearing the first exposes the second. A cross-site fetch with credentials: "include" sends a cookie only if it was set with SameSite=None and Secure.
response.set_cookie(
"session", token,
httponly=True,
secure=True,
samesite="none", # required for a different registrable domain
max_age=3600,
path="/",
)SameSite=Lax, the modern default, means the browser will not attach the cookie to a cross-site XHR at all, and the request arrives authenticated as nobody.
4. Reading custom headers on the client
X-Request-Id and pagination totals are invisible to fetch unless they are exposed, because the default exposed set is tiny.
app.add_middleware(CORSMiddleware, /* … */ expose_headers=["X-Request-Id", "X-Total-Count"])Without it, response.headers.get("X-Request-Id") returns null while DevTools shows the header on the response — the difference is the browser filtering, not the server.
5. Preflight caching and max_age
A 600-second max_age removes two round trips per endpoint from every page load. Chromium caps the value at 7200 seconds; anything larger is clamped, and max_age=-1 is treated as no caching.
max_age=7200 # the largest value Chromium honoursPreflight is also skipped entirely for "simple" requests — GET/POST with Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain. A JSON body forces a preflight, which is why changing a submission to FormData sometimes "fixes CORS".
6. Proxying instead of loosening CORS
When the frontend and API share a deploy, a same-origin proxy removes the problem rather than configuring around it: Next.js rewrites, NGINX proxy_pass, or Vercel rewrites. Requests then never cross origins, no Origin header is sent, and credentials behave like a plain page load.
Common Compilation/Runtime Mistakes & Version Gotchas
["*"]withallow_credentials=True. Invalid by spec; older Starlette sends*on requests without a cookie header.- Middleware added after the app starts serving.
add_middlewaremust precede startup; a late call raises or is ignored depending on the version. allow_methodsdefault. It is["GET"]unless you pass["*"], and aDELETEthen fails at preflight with a 400.allow_headersandAuthorization. Not in the safelisted set; every bearer-token app must list it.- Trailing slashes and
www. An origin is an exact string match, not a hostname match. CORSMiddlewareinside a mounted sub-app. The sub-app's middleware does not apply to sibling routes; mount order decides.- Proxy stripping
Origin. Some ingress configs drop it, and then no CORS header is produced at all.
Related tools. Inspect the JSON error body your handler returns with the JSON formatter, reproduce a failing request outside the browser with cURL to code and compare its headers against the browser's, and decode the session cookie's claims with the JWT decoder when the request arrives unauthenticated.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.