Skip to content

CORS Issue: FastAPI Behind Cloudflare + AWS ALB - Middleware Never Execute

0

I have a FastAPI application deployed on AWS ECS behind an Application Load Balancer (ALB) and Cloudflare. CORS requests from https://app.******.com to https://backend.******.com fail with "Disallowed CORS origin", but the same requests work fine from the Amplify domain https://main.d3irc2sl9wtr58.amplifyapp.com.

I discovered that FastAPI's CORS middleware is never executing with conclusion that the infrastructure is intercepting and blocking CORS requests before they reach the application.

asked 10 months ago209 views

1 Answer
0

This is almost certainly infrastructure-level CORS handling before the request reaches FastAPI, not a FastAPI bug. When Cloudflare sits in front of an AWS Application Load Balancer, Cloudflare can intercept or synthesize responses to OPTIONS preflight requests (via proxying, cache rules, WAF, or “Automatic OPTIONS” behavior), which means the request never reaches your FastAPI app and its CORS middleware never runs—hence the “Disallowed CORS origin.” This explains why it works from the Amplify domain (likely bypassing Cloudflare) but fails from your custom domain. The fix is to ensure Cloudflare forwards OPTIONS requests to the origin unmodified: disable caching/WAF rules for OPTIONS, avoid Transform Rules adding/removing CORS headers, set the backend hostname to DNS-only (gray cloud) for testing, or explicitly allow/forward OPTIONS in Cloudflare. Also confirm the ALB listener allows OPTIONS and does not return fixed responses. Once Cloudflare stops handling preflight itself, FastAPI’s CORS middleware will execute correctly.

answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.