Middleware
Middleware allows you to run custom code during the handling of events in your app.
Example: Logging
Reflex includes a built in middleware that logs all events to the console. Let's see how it works.
class LoggingMiddleware(rx.Middleware):
def preprocess(self, app, state, event):
print(f"Event {event}")
def postprocess(self, app, state, event, update):
print(f"Update {update}")
Middleware classes must inherit from rx.Middleware
. They have two functions that can be overridden: preprocess
and postprocess
.
The logging middleware just logs the incoming event before it is processed, and the delta after the state is updated. More complicated middleware can modify the actual event or state along the way.
You can add middleware during app creation.
app = rx.App(middleware=[LoggingMiddleware()])