Apply the CORS middleware once per request
FA
3h ago+15+15+01234567890123456789-23-23-01234567890123456789
Why
Every backend response repeats Origin in Vary. Without an api_transformer a response carries Vary: Origin, Origin. With a Starlette or FastAPI api_transformer it carries Vary: Origin, Origin, Origin, also on /ping.
#7624 meant to apply CORS once ("Requests no longer pass through … duplicate CORS middleware"). The outer CORS layer in App.__call__ was added, but the internal API and each Starlette transformer kept a CORS layer of their own. Each layer runs the origin check and appends Origin to Vary. Each layer overwrites access-control-allow-origin, so the tests named "exactly once" did not see the extra layers.
What changed
- Remove the CORS layer on the internal API and on each Starlette or FastAPI
api_transformer, and theApp._add_corshelper that added them. - The outer layer stays. It covers the internal API, the transformer routes, the routes that a callable transformer adds, and the 500 responses of the outermost error handler.
- Reflex no longer adds CORS middleware to the app passed as
api_transformer. An app served throughapp()behaves the same.
How tested
- Regression test first (3c3f3d09f):
test_api_transformer_routes_get_cors_headersandtest_unhandled_route_error_gets_cors_headersnow compare the completeVaryvalue. Before the fix:assert ['Origin, Origin'] == ['Origin']. After the fix: they pass. - The tests that called
App._add_corsnow useApp._cors_options(). - Before the fix, a dev app with a Starlette
api_transformeranswered/pingand/_reflex/sessionwithvary: Origin, Origin, Originin Chromium. I did not run the app again after the fix. The unit tests pin the single value. tests/unitspasses.ruff check,ruff format --checkandpyrightare clean.
Known limits
test_registered_middleware_are_classesnow iterates an empty list, because Reflex registers no middleware on the internal API. I kept it as a guard for middleware that is added later.
Type of change
- Bug fix (non-breaking change which fixes an issue)