# RuntimeError: Middleware 'CORSMiddleware' must be added before 'TrustedHostMiddleware' to work correctly.

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

## Root Cause

The order of middleware matters in FastAPI; some middleware depend on others being applied first.

## Version Compatibility

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

## Workarounds

1. **Add middleware in the correct order** (95% success)
   ```
   app.add_middleware(CORSMiddleware, allow_origins=['*'])
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com'])
   ```
2. **Check FastAPI documentation for middleware order** (90% success)
   ```
   Consult official docs for recommended order.
   ```

## Dead Ends

- **Ignoring the order and adding randomly** — May cause CORS or host validation issues. (90% fail)
- **Removing one middleware to avoid the error** — Loses functionality. (70% fail)
