CodexBloom - Programming Q&A Platform

FastAPI: How to handle CORS for multiple origins with wildcard subdomains?

👀 Views: 169 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
fastapi cors web-development Python

Could someone explain I can't seem to get I've hit a wall trying to I'm reviewing some code and I'm currently developing a FastAPI application and need to enable CORS for multiple origins, specifically handling wildcard subdomains. My application is running on FastAPI 0.68.0, and I have the following setup for CORS: ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ 'http://example.com', 'http://*.example.com' ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) ``` However, when I try to make requests from a subdomain, like `http://sub.example.com`, I'm getting a CORS behavior: ``` Access to fetch at 'http://sub.example.com/api/data' from origin 'http://sub.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` I attempted to specify the origins explicitly, but that becomes impractical as I have multiple subdomains. The wildcard `*` does not seem to work for subdomains in the `allow_origins` list. I also checked the FastAPI documentation and found no mention of supporting wildcard subdomains directly. Has anyone figured out a way to allow CORS for multiple subdomains dynamically or using a custom middleware? Any tips or workarounds would be greatly appreciated. What's the best practice here? Thanks for taking the time to read this! Thanks in advance! Hoping someone can shed some light on this.