Run middleware for stateless event handlers
Requested by Masen · project thread
Type of change
- Bug fix (non-breaking change which fixes an issue)
- This change requires a documentation update
Changes To Core Features:
Why. A stateless handler (#7673) ran before the processor's middleware pass, since there was no locked state to hand the middleware. A gate installed as middleware, such as reflex-enterprise's AuthMiddleware, never saw those events, so any websocket client could fire a stateless handler unauthenticated. REST and MCP surfaces were not affected.
What. BaseStateEventProcessor._execute_event now locks the client's root state for the middleware pass when any installed middleware has preprocess_stateless on, then releases it and runs the handler without a state as before. The flag is a new class attribute on rx.Middleware, on by default so a gate covers everything unless it opts out. HydrateMiddleware opts out, since only the hydrate event concerns it, so a stateless handler whose app installs only such middleware still never waits for the lock. MiddlewareMixin._preprocess skips opted-out middleware for stateless events.
The blocking-update emit shared by both paths is factored into _emit_update.
Tests. tests/units/reflex_base/event/processor/test_base_state_processor.py: a gating middleware blocks a stateless handler, sees the root state, and lets it through once state allows; an opted-out middleware never sees stateless events and the handler still runs while another handler holds the token's lock. The gate test fails on main.
Docs. docs/events/decentralized_event_handlers.md describes the middleware behaviour. News fragments for reflex and reflex-base.
Companion: reflex-dev/reflex-enterprise#286 makes AuthMiddleware gate stateless handlers once this lands.
- Tests, ruff and pyright pass locally (
tests/units: 8100 passed; the one error is a missing Playwright browser in this sandbox).
Generated by Claude Code