Middleware (WSGI) (Flask)

Middleware in Flask is WSGI middleware: a wrapper around the entire application that processes every request and response at the server level, below Flask's routing. It is used for concerns like proxy handling, compression, or request profiling.

Flask

True middleware sits at the WSGI layer, wrapping app.wsgi_app so it sees raw requests before Flask routes them and responses after Flask builds them. This is different from request hooks (before_request), which run inside Flask once a request context exists.

You add WSGI middleware by reassigning app.wsgi_app = SomeMiddleware(app.wsgi_app). A common real-world example is ProxyFix from werkzeug, which corrects request.remote_addr and the scheme when your app runs behind a reverse proxy like nginx.

For most app-level logic — authentication, loading the user, adding headers — request hooks are simpler and have access to Flask's context. Reach for WSGI middleware only when you need to operate outside or around the entire Flask app.

Syntax

app.wsgi_app = Middleware(app.wsgi_app)

Examples

Python

from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
# Now request.remote_addr reflects the real client behind the proxy

Learn it in a lesson

See also

Back to the Dictionary