Skip to content

CORS (Cross-Origin Resource Sharing)

CORS (Cross-Origin Resource Sharing) allows browsers to make requests to your API from different domains. Without CORS, browsers block these requests.

from justapi import JustAPIApp
app = JustAPIApp()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

For local development, allow all origins:

from justapi import JustAPIApp
from starlette.middleware.cors import CORSMiddleware
app = JustAPIApp()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)

Never use allow_origins=["*"] in production. It defeats the purpose of CORS restrictions.

In production, specify exactly which origins are allowed:

app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://app.example.com",
"https://admin.example.com",
],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
Parameter Type Description
allow_origins list[str] Allowed origins (["*"] for all)
allow_methods list[str] HTTP methods to allow
allow_headers list[str] Request headers to allow
allow_credentials bool Allow cookies and auth headers
expose_headers list[str] Headers the browser can read