CORSMiddleware
TheCORSMiddleware allows you to configure Cross-Origin Resource Sharing (CORS) for your FastAPI application, enabling browsers to make cross-origin requests from frontend applications.
Usage
Parameters
A list of origins that are allowed to make cross-origin requests. Use
["*"] to allow any origin. For example: ["https://example.com", "https://app.example.com"].A regex pattern string to match against origins. For example:
https://.*\.example\.com.A list of HTTP methods that are allowed for cross-origin requests. Use
["*"] to allow all standard methods. Default is ["GET"].A list of HTTP request headers that are allowed for cross-origin requests. Use
["*"] to allow all headers. The Accept, Accept-Language, Content-Language, and Content-Type headers are always allowed for CORS requests.Indicates whether cookies should be supported for cross-origin requests. If set to
True, the allow_origins cannot be ["*"], and must specify origins explicitly.A list of HTTP response headers that should be made accessible to the browser. By default, only simple response headers are exposed.
The maximum time in seconds that browsers can cache CORS responses. Default is 600 seconds (10 minutes).
Example with Multiple Origins
Security Considerations
- Avoid using
allow_origins=["*"]in production unless your API is truly public - When using
allow_credentials=True, you must specify explicit origins - Use
allow_origin_regexcarefully to avoid overly permissive patterns - Consider limiting
allow_methodsandallow_headersto only what your application needs