Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readPython
#Python#FastAPI#CORS#Browser
3D illustration of a browser window cube separated from an API cube by a blocked gate, a wildcard star token rejected at the gate

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.

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

bash
# 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

ConfigurationPreflight resultCredentialed fetchCorrect for
["*"], credentials off* allowed* allowedpublic read-only APIs
["*"], credentials onorigin echoed, new Starletteblocked on older versionsnothing
explicit list, credentials onorigin echoedallowedcookie or bearer auth
allow_origin_regex=".*", credentials onorigin echoedalloweddynamic preview hosts
no middlewareno headersblockednever
MistakeBrowser symptomFix
trailing slash in originno Allow-Origin headerstrip the slash
allow_methods missing PATCHpreflight 400 "Disallowed CORS method"list every verb used
custom header not allowedpreflight 400 "Disallowed CORS headers"add to allow_headers
www mismatchsilent block on that hostadd both origins
500 bypasses middlewareCORS error, 500 in network tabhandler 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.

python
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.

python
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.

python
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.

python
max_age=7200 # the largest value Chromium honours

Preflight 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

  • ["*"] with allow_credentials=True. Invalid by spec; older Starlette sends * on requests without a cookie header.
  • Middleware added after the app starts serving. add_middleware must precede startup; a late call raises or is ignored depending on the version.
  • allow_methods default. It is ["GET"] unless you pass ["*"], and a DELETE then fails at preflight with a 400.
  • allow_headers and Authorization. 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.
  • CORSMiddleware inside 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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.