CORS

Allowing a Frontend to Call Your API

Browsers block JavaScript on https://app.example.com from reading responses from https://api.example.com unless the API allows it with CORS headers.

Example

The browser first sends a "preflight" OPTIONS request. An allowed origin gets access-control-allow-origin back; any other origin is refused:

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

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

@app.get("/courses")
def courses():
    return ["HTML", "CSS"]

Requests and responses

OPTIONS /courses
→ 200 OK
  access-control-allow-origin: http://localhost:5173
OPTIONS /courses
→ 400 Disallowed CORS origin
  access-control-allow-origin: None

Note: Do not use allow_origins=["*"] together with credentials. List your real frontend origins.