]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
📝 Clarify the middleware execution order in docs (#13699)
authorMotov Yurii <109919500+YuriiMotov@users.noreply.github.com>
Tue, 17 Jun 2025 07:42:41 +0000 (09:42 +0200)
committerGitHub <noreply@github.com>
Tue, 17 Jun 2025 07:42:41 +0000 (09:42 +0200)
docs/en/docs/tutorial/middleware.md

index 4f7980165ca67dedd2e00345c01f4e5ecb80ec85..b7c03a3199b7e9d6270a3034ca909ff9106c5798 100644 (file)
@@ -65,6 +65,29 @@ Here we use <a href="https://docs.python.org/3/library/time.html#time.perf_count
 
 ///
 
+## Multiple middleware execution order
+
+When you add multiple middlewares using either `@app.middleware()` decorator or `app.add_middleware()` method, each new middleware wraps the application, forming a stack. The last middleware added is the *outermost*, and the first is the *innermost*.
+
+On the request path, the *outermost* middleware runs first.
+
+On the response path, it runs last.
+
+For example:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+This results in the following execution order:
+
+* **Request**: MiddlewareB → MiddlewareA → route
+
+* **Response**: route → MiddlewareA → MiddlewareB
+
+This stacking behavior ensures that middlewares are executed in a predictable and controllable order.
+
 ## Other middlewares
 
 You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}.