CORS allow-lists
Wildcard CORS is the default in almost every FastAPI tutorial and it is almost never what you want in production. allow_origins=["*"] plus allow_credentials=True is actually ignored by browsers because the combination is insecure. An explicit allow-list fixes both the policy and the browser behaviour.
import os
from fastapi.middleware.cors import CORSMiddleware
allowed_origins = [
origin.strip()
for origin in os.getenv("ALLOWED_ORIGINS", "").split(",")
if origin.strip()
]
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins or ["http://localhost:3000"],
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "Idempotency-Key", "X-Request-ID"],
expose_headers=["X-Request-ID"],
)Read origins from the environment. Restrict methods to what the API actually uses. List headers explicitly so unknown headers get rejected at the preflight instead of confusing the endpoint later. Expose X-Request-ID so client-side code can surface it in bug reports.
Matching exercise: CORS header purpose
Loading practice…
Quiz: Quiz
Loading practice…