# AssertionError: Cannot add middleware after an application has started

- **ID:** `python/starlette-middleware-order-response-headers`
- **Domain:** python
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 0.30+ | active | — | — |

## 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

- **** — The middleware is never added; headers/logging silently missing. (85% fail)
- **** — Startup fires after the middleware stack is built; assertion still raised. (90% fail)
