High severity intermediate · Fix: 5-10 min

RuntimeError

fastapi.applications.FastAPI RuntimeError

What this error means
FastAPI raises a RuntimeError when authentication middleware is added after other middleware that short-circuits requests, causing auth to be skipped.

Stack trace

traceback
RuntimeError: Middleware must be added before any routes are registered or other middleware that handles requests is added.
QUICK FIX
Move the authentication middleware registration to the top, before any route or other middleware registrations.

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

1

Authentication middleware added after route handlers or other middleware that handles requests

✓ Fix

Register authentication middleware before adding any routes or middleware that can short-circuit requests.

2

Using third-party middleware that processes requests before auth middleware

✓ Fix

Add authentication middleware as the very first middleware in the FastAPI app to ensure it runs first.

3

Adding middleware after app startup or after calling app.include_router()

✓ Fix

Add all middleware before including routers or starting the app to maintain correct execution order.

Code: broken vs fixed

Broken - triggers the error
python
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
Fixed - works correctly
python
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")
Moved authentication middleware registration before route definitions to ensure it runs first and prevent RuntimeError.

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.

Python 3.9+ · fastapi >=0.60.0 · tested on 0.95.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.