← Back to Tutorials
24. CORS (Cross-Origin Resource Sharing)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Allow all origins (development only)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Specific origins (production)
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://myfrontend.com",
"https://app.myfrontend.com",
],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
expose_headers=["X-Total-Count"],
max_age=600,
)
# Why CORS?
# Browsers block cross-origin requests by default.
# CORS headers tell the browser: "This server allows your origin."
💡 Note: Use allow_origins=["*"] only during development. In production, list specific origins to prevent malicious sites from accessing your API.
✏️ Exercise: Set up CORS to allow only your localhost:3000 frontend. Test with a simple fetch() from a different port — it should be blocked.