Configure and attach CORS middleware.
(app: FastAPI)
| 88 | |
| 89 | |
| 90 | def add_cors_middleware(app: FastAPI) -> None: |
| 91 | """Configure and attach CORS middleware.""" |
| 92 | # Dev defaults; override via CORS_ALLOW_ORIGINS (comma-separated) |
| 93 | default_origins = [ |
| 94 | "http://localhost:5173", |
| 95 | "http://127.0.0.1:5173", |
| 96 | ] |
| 97 | env_origins = os.getenv("CORS_ALLOW_ORIGINS") |
| 98 | if env_origins: |
| 99 | origins = [o.strip() for o in env_origins.split(",") if o.strip()] |
| 100 | origin_regex = None |
| 101 | else: |
| 102 | origins = default_origins |
| 103 | # Helpful in dev: allow localhost/127.0.0.1 on any port |
| 104 | origin_regex = r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$" |
| 105 | |
| 106 | app.add_middleware( |
| 107 | CORSMiddleware, |
| 108 | allow_origins=origins, |
| 109 | allow_origin_regex=origin_regex, |
| 110 | allow_credentials=True, |
| 111 | allow_methods=["*"], |
| 112 | allow_headers=["*"], |
| 113 | expose_headers=["X-Correlation-ID"], |
| 114 | max_age=600, |
| 115 | ) |
| 116 | |
| 117 | |
| 118 | def add_middleware(app: FastAPI): |