Skip to main content
CORS (Cross-Origin Resource Sharing) is a security feature that controls which domains can access your API from web browsers. FastAPI provides 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.
Without proper CORS configuration, frontend applications running on different domains won’t be able to access your API.

Basic Setup

Configuration Parameters

allow_origins

List of origins that are allowed to make cross-origin requests:
Using allow_origins=["*"] allows any domain to access your API. Only use this in development or for truly public APIs.

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:
When a browser makes a request to /items, it first sends:
The middleware responds with CORS headers, then the actual GET request proceeds.
Preflight requests are cached based on max_age. Increase this value to reduce preflight request overhead.

Wildcard Subdomains

To allow all subdomains of a domain:

Testing CORS

Test your CORS configuration:
Look for these response headers:
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers
  • Access-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 SameSite attribute

See Also