python
runtime_error
ai_generated
true
RuntimeError: Cannot add middleware after an application has started
ID: python/starlette-middleware-order-500
80%Fix Rate
86%Confidence
0Evidence
2024-11-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
add_middleware is called after the ASGI app has begun handling requests, e.g. inside a startup event or a route.
generic中文
在 ASGI 应用开始处理请求后(例如在 startup 事件或路由中)调用了 add_middleware。
Workarounds
-
93% success
Register middleware at module level before the app starts: app.add_middleware(GZipMiddleware)
-
85% success
Use lifespan for startup logic, not middleware registration.
Dead Ends
Common approaches that don't work:
-
90% fail
Startup runs after the middleware stack is built; the error is raised.
-
75% fail
The middleware is never applied, so behavior silently differs.