How to Use CORS Middleware in FastAPI for Cross-Origin Requests
To use
CORS middleware in FastAPI, import CORSMiddleware from fastapi.middleware.cors and add it to your app with add_middleware. Configure allowed origins, methods, and headers to control cross-origin access.Syntax
The CORSMiddleware is added to a FastAPI app using add_middleware. You specify allowed_origins (list of URLs allowed to access your API), allowed_methods (HTTP methods allowed), and allowed_headers (headers clients can send).
This middleware handles the CORS preflight requests and sets the proper headers in responses.
python
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://example.com", "http://localhost:3000"], allow_methods=["GET", "POST"], allow_headers=["*"], )
Example
This example shows a FastAPI app with CORS middleware allowing requests from http://localhost:3000 and https://myfrontend.com. It permits all HTTP methods and headers. The app has a simple root endpoint returning a greeting.
python
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost:3000", "https://myfrontend.com", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") async def read_root(): return {"message": "Hello from FastAPI with CORS!"}
Output
Running the app and making a GET request from allowed origins returns JSON: {"message": "Hello from FastAPI with CORS!"} with proper CORS headers.
Common Pitfalls
- Not specifying allowed_origins: If you leave
allow_originsempty or omit it, no cross-origin requests will be allowed. - Using
allow_origins=["*"]withallow_credentials=True: This combination is invalid and will cause errors because credentials cannot be shared with all origins. - Forgetting to add middleware before routes: Middleware must be added before defining routes to work properly.
python
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # Wrong: allow_credentials=True with allow_origins=["*"] causes error app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Right way: # app.add_middleware( # CORSMiddleware, # allow_origins=["http://localhost:3000"], # allow_credentials=True, # allow_methods=["*"], # allow_headers=["*"], # )
Quick Reference
Remember these key points when using CORS middleware in FastAPI:
- allow_origins: List of allowed URLs, cannot be
["*"]ifallow_credentials=True. - allow_methods: HTTP methods allowed, use
["*"]for all. - allow_headers: Headers allowed from client,
["*"]allows all. - allow_credentials: Whether to allow cookies or auth headers.
Key Takeaways
Add CORSMiddleware to your FastAPI app using add_middleware before defining routes.
Set allow_origins to the list of trusted URLs to enable cross-origin requests.
Avoid using allow_origins=["*"] with allow_credentials=True to prevent errors.
Use allow_methods and allow_headers to control which HTTP methods and headers are accepted.
CORS middleware automatically handles preflight OPTIONS requests and sets response headers.