CORS (Cross-Origin Resource Sharing)
Basic CORS
Section titled “Basic CORS”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=["*"],)Permissive CORS (Development)
Section titled “Permissive CORS (Development)”For local development, allow all origins:
from justapi import JustAPIAppfrom 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.
Restrictive CORS (Production)
Section titled “Restrictive CORS (Production)”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"],)Options
Section titled “Options”| 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 |
See Also
Section titled “See Also”- Middleware — general middleware usage
- Security Policy — security best practices