dnscorssubdomainfastapi-middleware

CORS header ‘Access-Control-Allow-Origin’ missing error for new Cloudfare domain


My frontend, registered to the playlistmoodevaluator.com domain on Cloudflare, routes to a React CRA-based app hosted on Render. My backend, registered to the api.playlistmoodevaluator.com subdomain on Cloudflare, routes to a FastAPI python backend hosted on Fly.io.

The first request to my backend fails with Reason: CORS header ‘Access-Control-Allow-Origin’ missing, despite the fact that my FastAPI backend is configured with a CORS Middleware to accept requests from that frontend domain.

I ensured that my backend is configured to accept requests from my frontend, like so:

origins = [
    "https://playlistmoodevaluator.com",
    "https://www.playlistmoodevaluator.com",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Here is a screenshot of the error:

enter image description here

As you can see in the screenshot attached below, this exact origin (https://playlistmoodevaluator.com), is expected by my backend’s Middleware and should be accepted. This process was working until I registered my domain with Cloudflare and started routing my traffic through my new domain.


Solution

  • I registered my Cloudfare domain in "Full" SSL mode, meaning that all domains/subdomains must use SSL/TSL (this is recommended).

    I easily issued an SSL cert for my frontend (deployed on Render) that was registered to my main domain, but my backend (hosted on Fly.io) did not have an SSL cert issued for my subdomain. Thus my subdomain was routing to a non HTTPS-server, and the Cloudfare DNS was rejecting the traffic since the "Full" configuration requires HTTPS.

    After going to Fly.io and issuing an SSL cert for my subdomain, my app worked as expected!!

    tldr; if you use "Full" SSL mode for your DNS, both frontend and backend must have SSL certs issued for their respective domains!