How to Enable and Configure CORS Middleware in FastAPI Boilerplate
The benavlabs/fastapi-boilerplate provides built-in CORS support through the CORSSettings class in src/app/core/config.py and automatic middleware registration in src/app/core/setup.py, allowing configuration via environment variables or programmatic instantiation.
The benavlabs/fastapi-boilerplate repository streamlines cross-origin resource sharing setup for FastAPI applications. You can enable and configure CORS middleware using environment variables or by modifying the CORSSettings class defaults. This guide walks through the actual implementation in the source code and shows you how to customize the settings for production or development environments.
How CORS Works in the Boilerplate
The CORS implementation consists of two integrated components: a Pydantic settings class that defines allowed origins, and conditional middleware registration in the application factory.
CORSSettings Configuration Class
Located in src/app/core/config.py (lines 172-176), the CORSSettings class inherits from pydantic.BaseSettings to provide environment-driven configuration:
class CORSSettings(BaseSettings):
CORS_ORIGINS: list[str] = ["*"]
CORS_METHODS: list[str] = ["*"]
CORS_HEADERS: list[str] = ["*"]
Because it uses BaseSettings, you can override these defaults using environment variables with matching names. The defaults allow all origins, methods, and headers, which is suitable for development but should be restricted for production.
Middleware Registration in the Application Factory
The src/app/core/setup.py file (lines 215-223) contains the logic that conditionally registers CORSMiddleware. Inside the application setup logic, the code checks if the settings instance includes CORS configuration:
if isinstance(settings, CORSSettings):
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_methods=settings.CORS_METHODS,
allow_headers=settings.CORS_HEADERS,
)
This pattern ensures the middleware is only added when CORSSettings is present, keeping the application lightweight when CORS is not needed.
Configuration Methods
You have three primary ways to enable and configure CORS middleware in this boilerplate, depending on your deployment strategy.
Method 1: Environment Variables (Recommended)
For production deployments, configure CORS via environment variables. Create or modify your .env file with specific domains and methods:
CORS_ORIGINS=["https://example.com","https://app.example.com"]
CORS_METHODS=["GET","POST","OPTIONS"]
CORS_HEADERS=["Authorization","Content-Type"]
When the application starts, CORSSettings automatically parses these values and setup.py registers the middleware with your restrictions.
Method 2: Programmatic Configuration
For testing scenarios or when you need dynamic configuration, instantiate CORSSettings directly and pass it to the application factory:
from src.app.core.config import CORSSettings
from src.app.core.setup import create_app
custom_cors = CORSSettings(
CORS_ORIGINS=["http://localhost:3000"],
CORS_METHODS=["GET", "POST"],
CORS_HEADERS=["*"]
)
app = create_app(settings=custom_cors)
The create_app function detects the CORSSettings instance and installs the middleware with your custom values before returning the FastAPI application instance.
Method 3: Default Allow-All Setup
To enable CORS immediately without configuration, simply start the application. The defaults in CORSSettings permit all origins, methods, and headers:
uvicorn src.app.main:app --reload
This configuration is active by default because src/app/main.py initializes the settings object with CORSSettings defaults, triggering the middleware registration in setup.py.
Verifying Your CORS Configuration
Test that your CORS middleware is active and correctly configured using curl. Send a request with an Origin header and inspect the response headers:
curl -I -H "Origin: https://example.com" http://localhost:8000/api/v1/health
If the origin is allowed, the response includes access-control-allow-origin: https://example.com. If the middleware rejects the origin or is not configured, this header will be absent from the response.
Summary
- The benavlabs/fastapi-boilerplate enables CORS through the
CORSSettingsclass insrc/app/core/config.pyand conditional registration insrc/app/core/setup.py. - Configure CORS via environment variables (
CORS_ORIGINS,CORS_METHODS,CORS_HEADERS) for production security. - The middleware only registers when the settings object is an instance of
CORSSettings, ensuring minimal overhead. - Defaults allow all traffic (
["*"]), which you should override before deploying to production. - Verify configuration using curl to check for the
access-control-allow-originheader in responses.
Frequently Asked Questions
Where is the CORS configuration defined in the fastapi-boilerplate?
The configuration is defined in src/app/core/config.py within the CORSSettings class (lines 172-176). This Pydantic BaseSettings subclass defines three fields: CORS_ORIGINS, CORS_METHODS, and CORS_HEADERS, each defaulting to ["*"].
How do I restrict CORS to specific domains in production?
Set the CORS_ORIGINS environment variable to a JSON array of allowed domains: CORS_ORIGINS=["https://yourdomain.com"]. The CORSSettings class reads this variable during instantiation, and src/app/core/setup.py (lines 215-223) uses these values when registering CORSMiddleware.
Can I disable CORS entirely in the boilerplate?
Yes. Since the middleware only registers when isinstance(settings, CORSSettings) returns True, you can disable CORS by ensuring your application settings object does not include or inherit from CORSSettings. Alternatively, set all CORS lists to empty arrays in your environment configuration.
Why are my CORS headers not showing in the response?
Verify that the CORSSettings instance is actually being passed to the application factory in src/app/main.py. If the settings object passed to create_app is not an instance of CORSSettings, the conditional block in src/app/core/setup.py skips middleware registration. Also ensure your origin exactly matches the values in CORS_ORIGINS, including protocol and port.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →