Middleware in FastAPI

Difficulty: Intermediate

Question

What is middleware in FastAPI, how do you add it, and what are typical use cases?

Answer

Middleware is code that wraps every request and response passing through the app: it runs before the request reaches any route and after the response is produced. In FastAPI you add it with @app.middleware("http") for a quick function, or app.add_middleware(SomeMiddleware, **options) for a class such as CORSMiddleware, GZipMiddleware or TrustedHostMiddleware.

How the middleware stack works

Middleware forms layers around the app, like an onion:

  1. The request enters the outermost middleware.
  2. Each layer can inspect or modify it, short-circuit with its own response, or call the next layer (await call_next(request)).
  3. The innermost layer is the router, which runs dependencies and your handler.
  4. The response travels back out through the same layers in reverse.

Order matters. With app.add_middleware, the last one added is the outermost and runs first on the way in. If you add a logging middleware after CORS, logging sees requests before CORS does. Starlette also wraps everything in ServerErrorMiddleware (outermost) and ExceptionMiddleware (innermost).

Typical use cases

  • CORS for browser frontends on another origin.
  • Request IDs and structured logging: generate or forward X-Request-ID, log method, path, status and duration.
  • Timing / metrics: Prometheus histograms of latency.
  • Compression: GZipMiddleware(minimum_size=1000).
  • Security headers and host checks: TrustedHostMiddleware, HTTPSRedirectMiddleware.
  • Sessions: SessionMiddleware for signed cookie sessions.

Middleware vs dependencies

AspectMiddlewareDependency
Runs forEvery request, including 404sOnly routes that declare it
Sees responseYesOnly indirectly
Access to parsed paramsNo, raw request onlyYes, typed values
Shows in OpenAPINoYes
Good forCross-cutting HTTP concernsAuth, DB sessions, per-route logic

Authentication usually belongs in a dependency, so routes declare it explicitly and docs show the security scheme.

Gotchas

  • @app.middleware("http") uses Starlette's BaseHTTPMiddleware. It is convenient but adds overhead and historically had issues with streaming responses and context variables. For hot paths, write a pure ASGI middleware (a class with async def __call__(self, scope, receive, send)).
  • Reading await request.body() in middleware consumes the stream; be careful if handlers also need it.
  • CORS: browsers reject Access-Control-Allow-Origin: * together with credentials, so list explicit origins when allow_credentials=True.
  • Exceptions raised inside your handler are converted to responses by exception handlers before your middleware sees them, but errors raised inside middleware itself become 500s.
The middleware onion. Requests travel inward through each layer and responses travel back out.
  1. ServerErrorMiddleware: Outermost; turns crashes into 500s.
  2. Last added user middleware: For example request ID and timing.
  3. First added user middleware: For example CORS.
  4. ExceptionMiddleware: Runs your exception handlers.
  5. Router and path operation: Dependencies and your handler.

Code examples

CORS plus a request ID and timing middleware

import time
import uuid

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.in", "http://localhost:5173"],
    allow_credentials=True,              # so explicit origins, never "*"
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)

@app.middleware("http")                  # added last, so it is the outermost
async def request_context(request: Request, call_next):
    request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
    start = time.perf_counter()
    response = await call_next(request)  # everything inside runs here
    elapsed_ms = (time.perf_counter() - start) * 1000
    response.headers["X-Request-ID"] = request_id
    response.headers["X-Process-Time-ms"] = f"{elapsed_ms:.1f}"
    return response

The decorator-based middleware wraps CORS and GZip because it was registered last. perf_counter is the right clock for measuring durations.

A pure ASGI middleware

class SecurityHeadersMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)

        async def send_with_headers(message):
            if message["type"] == "http.response.start":
                headers = message.setdefault("headers", [])
                headers.append((b"x-content-type-options", b"nosniff"))
            await send(message)

        await self.app(scope, receive, send_with_headers)

# app.add_middleware(SecurityHeadersMiddleware)

Pure ASGI middleware avoids BaseHTTPMiddleware overhead and works correctly with streaming responses.

Key points

  • Middleware wraps every request and response, including 404s
  • Last added middleware is the outermost and runs first
  • @app.middleware('http') is BaseHTTPMiddleware; pure ASGI is faster for hot paths
  • Auth and DB sessions usually belong in dependencies, not middleware
  • Wildcard CORS origin cannot be combined with credentials

Common follow-up questions

  • How does CORS preflight work and what does CORSMiddleware do with OPTIONS requests?
  • Why might BaseHTTPMiddleware be a problem for streaming responses?
  • Would you put authentication in middleware or a dependency? Why?
  • How would you propagate a request ID into your logs?

Interview tips

  • Explain the onion model and ordering; it is the detail most candidates miss
  • Contrast middleware with dependencies using a concrete example
  • Mention pure ASGI middleware to show depth beyond the decorator

Concepts covered

middleware, CORSMiddleware, middleware order, BaseHTTPMiddleware, pure ASGI middleware

More FastAPI Interview questions