Script Valley
FastAPI: Build Production Python APIs
Authentication and SecurityLesson 4.4

How to configure CORS in FastAPI for frontend integration

CORSMiddleware, allow_origins, allow_methods, allow_headers, allow_credentials, preflight requests, wildcard origins, production vs development config

CORS Configuration in FastAPI

CORS (Cross-Origin Resource Sharing) allows browsers to call your API from a different domain. Without it, requests from your frontend domain will be blocked by the browser.

Adding CORSMiddleware

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://myapp.com", "http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

The middleware intercepts preflight OPTIONS requests and responds with the correct headers before the actual request is processed.

Configuration rules

In development, add http://localhost:3000 (or your Vite/CRA port). In production, list only exact allowed origins. Never use allow_origins=["*"] with allow_credentials=True โ€” browsers block this combination because it would allow any site to send credentialed requests to your API.

# Development only โ€” do not use in production with credentials
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

If your frontend sends cookies or Authorization headers, you need allow_credentials=True and an exact origin list โ€” wildcards are disallowed by the CORS spec in that case.

Up next

How to add rate limiting and request size limits to FastAPI

Sign in to track progress

How to configure CORS in FastAPI for frontend integration โ€” Authentication and Security โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley