# AssertionError: Middleware must be added before routes

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

## Root Cause

在 Starlette 中，尝试在路由已定义后添加中间件，导致断言失败。

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **** (90% success)
   ```
   app = Starlette(routes=routes, middleware=[Middleware(AuthenticationMiddleware)])
   ```
2. **** (85% success)
   ```
   app = Starlette()
app.add_middleware(AuthenticationMiddleware)
app.router.routes = routes
   ```

## Dead Ends

- **** — 虽然能解决，但代码冗余且不优雅。 (70% fail)
- **** — 中间件功能（如认证）将失效。 (80% fail)
