Register middlewares as late as possible #4155
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR moves the middleware registration from import time to the actual call of
ui.run
. Thereby the middlewares are also run before middlewares which are added by user code. See the the authentication example for an actual use-case where this is convinient:https://github.com/zauberzeug/nicegui/blob/09f4c34049b37907174bfe3109aae4b834f80863/examples/authentication/main.py#L28C2-L33C40
Without this change, the
RedirectResponse
does not work properly behind a reverse proxy with subpath or NiceGUI On Air, because the rewriting of the path prefix which is done by ourRedirectWithPrefixMiddleware
. FastAPI / Starlette call the middlewares in reverse order of registration. Therefore, without this PR, the user middleware is the last one added and hence called first, leaving the path unmodified.ToDos:
if __name__ in ('__mp_main__', '__main__')
guardui.run_with