patternpythonfastapiModerate
FastAPI CORS setup with CORSMiddleware
Viewed 0 times
CORScross-originCORSMiddlewareaccess-controlbrowser security
Error Messages
Problem
Browser requests to a FastAPI backend from a different origin fail with CORS errors when the server doesn't include the correct Access-Control-* headers.
Solution
Add CORSMiddleware from starlette. Be specific with allowed_origins in production — never use ['*'] when credentials are involved.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['https://app.example.com'], # or ['*'] for public APIs
allow_credentials=True,
allow_methods=['GET', 'POST', 'PUT', 'DELETE'],
allow_headers=['Authorization', 'Content-Type'],
)Why
CORS is enforced by the browser. The server must include Access-Control-Allow-Origin (and other headers) in responses — and in the preflight OPTIONS response — for the browser to allow the request.
Gotchas
- allow_origins=['*'] and allow_credentials=True together are invalid — browsers reject this combination
- Preflight OPTIONS requests must be handled — CORSMiddleware does this automatically
- CORS middleware must be added BEFORE other middleware that might return early (e.g., auth middleware)
- Wildcards in allow_origins don't support pattern matching — list exact origins or handle dynamically
Context
FastAPI backends consumed by browser-based frontends on different origins
Revisions (0)
No revisions yet.