CORSMiddleware to configure CORS policies.
Why CORS Matters
Browsers implement the same-origin policy, which prevents JavaScript running on one domain from accessing resources on another domain. CORS allows you to explicitly permit cross-origin requests.Basic Setup
Configuration Parameters
allow_origins
List of origins that are allowed to make cross-origin requests:allow_credentials
Whether to allow credentials (cookies, authorization headers) in cross-origin requests:When
allow_credentials=True, you cannot use allow_origins=["*"]. You must specify exact origins.allow_methods
HTTP methods allowed for cross-origin requests:allow_headers
HTTP headers allowed in cross-origin requests:expose_headers
Headers that browsers are allowed to access:max_age
How long browsers can cache CORS preflight responses (in seconds):Common Configurations
Development Setup
Permissive configuration for local development:Production Setup
Restrictive configuration for production:Environment-Based Configuration
Understanding Preflight Requests
Browsers send a preflight OPTIONS request before certain cross-origin requests:/items, it first sends:
Wildcard Subdomains
To allow all subdomains of a domain:Testing CORS
Test your CORS configuration:Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-HeadersAccess-Control-Allow-Credentials
Common Issues
Credentials with Wildcard Origins
Missing Headers
If your frontend sends custom headers, you must allow them:CORS with Authentication
When using authentication with CORS:
- Set
allow_credentials=True - Include “Authorization” in
allow_headers - Specify exact origins (no wildcards)
- Ensure cookies have the correct
SameSiteattribute
See Also
- Custom Middleware - Create custom middleware
- Behind a Proxy - Configure FastAPI behind a reverse proxy
- Security - Authentication and authorization