python config_error ai_generated true

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

ID: python/fastapi-middleware-order

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

FastAPI 中中间件的顺序很重要;某些中间件依赖于其他中间件先被应用。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. Ignoring the order and adding randomly 90% fail

    May cause CORS or host validation issues.

  2. Removing one middleware to avoid the error 70% fail

    Loses functionality.