python config_error ai_generated true

AssertionError: Cannot add middleware after an application has started

ID: python/starlette-middleware-order-response-headers

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.30+ active — — —

Root Cause

app.add_middleware() was called after the ASGI app had already started serving (e.g., inside a route or after TestClient instantiation).

generic

中文

在 ASGI 应用已经开始提供服务后调用了 app.add_middleware()(例如在路由内或 TestClient 实例化之后)。

Workarounds

  1. 95% success
    app = FastAPI()
    app.add_middleware(CORSMiddleware, allow_origins=['*'])
    # then define routes
  2. 90% success
    def create_app():
        app = FastAPI()
        app.add_middleware(...)
        return app

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The middleware is never added; headers/logging silently missing.

  2. 90% fail

    Startup fires after the middleware stack is built; assertion still raised.