Fix CORS Error in FastAPI
FastAPI does not add CORS headers by default. Your React app on port 3000 and FastAPI on port 8000 are different origins — the browser blocks the connection. Add CORSMiddleware before your routes and it works.
Browser Console Error
Access to fetch at 'http://localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.The fix
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourapp.com"], # your frontend domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/api/data")
def get_data():
return {"status": "ok"}
Add the middleware before route definitions. FastAPI handles OPTIONS preflight automatically once CORSMiddleware is mounted — you do not need to write OPTIONS handlers manually.
Development vs production
import os
dev_origins = ["http://localhost:3000", "http://localhost:5173"]
prod_origins = ["https://yourapp.com", "https://www.yourapp.com"]
origins = dev_origins if os.getenv("ENV") == "development" else prod_origins
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Why allow_origins=["*"] breaks with credentials
If your frontend sends cookies or an Authorization header, a wildcard origin will fail. The browser spec rejects this combination. Use an explicit origin list.
# Breaks when frontend uses credentials: 'include' allow_origins=["*"], allow_credentials=True # ❌ # Works allow_origins=["https://yourapp.com"], allow_credentials=True # ✅
vLLM and Ollama API backends
Running a language model API that a browser-based chat UI calls? Configure allowed origins at startup:
# vLLM vllm serve --host 0.0.0.0 --port 8000 \ --allowed-origins '["https://yourapp.com"]' # Ollama OLLAMA_ORIGINS=https://yourapp.com ollama serve
Starlette and raw ASGI apps
from starlette.middleware.cors import CORSMiddleware
from starlette.applications import Starlette
app = Starlette()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourapp.com"],
allow_methods=["*"],
allow_headers=["*"],
)
Test your FastAPI CORS config live →