RuntimeError
fastapi.applications.FastAPI RuntimeError
Stack trace
RuntimeError: Middleware must be added before any routes are registered or other middleware that handles requests is added.
Why it happens
FastAPI requires middleware to be added in the correct order because middleware is executed in the order it is added. If authentication middleware is added after middleware that handles or short-circuits requests, the auth middleware never runs, causing authentication failures and runtime errors.
Detection
Monitor startup logs for RuntimeError related to middleware order and verify that authentication middleware is registered before any route handlers or other middleware that can terminate requests.
Causes & fixes
Authentication middleware added after route handlers or other middleware that handles requests
Register authentication middleware before adding any routes or middleware that can short-circuit requests.
Using third-party middleware that processes requests before auth middleware
Add authentication middleware as the very first middleware in the FastAPI app to ensure it runs first.
Adding middleware after app startup or after calling app.include_router()
Add all middleware before including routers or starting the app to maintain correct execution order.
Code: broken vs fixed
from fastapi import FastAPI
from starlette.middleware.authentication import AuthenticationMiddleware
app = FastAPI()
@app.get("/secure")
async def secure_endpoint():
return {"message": "Secure"}
app.add_middleware(AuthenticationMiddleware, backend=MyAuthBackend()) # RuntimeError here import os
from fastapi import FastAPI
from starlette.middleware.authentication import AuthenticationMiddleware
app = FastAPI()
# Fixed: Add auth middleware before routes
app.add_middleware(AuthenticationMiddleware, backend=MyAuthBackend()) # Middleware order fixed
@app.get("/secure")
async def secure_endpoint():
return {"message": "Secure"}
print("App started with correct middleware order") Workaround
If you cannot reorder middleware immediately, wrap route handlers with explicit authentication checks as a temporary measure until middleware order is fixed.
Prevention
Always add authentication and critical middleware before any routes or other middleware to guarantee proper execution order and avoid runtime errors.