Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python FastAPI Middleware: CORS and Custom Middleware

Configure CORS and build custom middleware in FastAPI. Learn how middleware order works, when to use BaseHTTPMiddleware, and when to write pure ASGI middleware.

~3 min readPython
#FastAPI#Middleware#CORS#ASGI
Diagram of a FastAPI request passing through CORS and custom middleware layers before reaching the route handler

FastAPI uses Starlette's ASGI middleware system. Middleware sits between the ASGI server and your route handlers. It can inspect, modify, or reject requests and responses. The two most common uses are enabling CORS and adding cross-cutting logic such as logging, timing, or authentication. In practice, the important details are middleware execution order and when to use BaseHTTPMiddleware instead of a pure ASGI middleware.

Adding CORS Middleware

FastAPI ships with a built-in CORSMiddleware that handles cross-origin resource sharing. You add it via app.add_middleware() and configure allowed origins, methods, and headers.

python
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://example.com"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )

The allow_origins list controls which origins may access your API. If you only need public, credential-less requests, ["*"] is enough. For cookies or authorization headers, list explicit origins and set allow_credentials=True; under the CORS spec, a wildcard origin cannot be used with credentials. The middleware automatically handles preflight OPTIONS requests and adds the appropriate Access-Control-Allow-* headers to responses.

Building Custom Middleware

The simplest way to write custom middleware in FastAPI is to subclass starlette.middleware.base.BaseHTTPMiddleware and implement an async dispatch method. The method receives a Request and a call_next function.

python
from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request import time class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): start = time.perf_counter() response = await call_next(request) duration = time.perf_counter() - start response.headers["X-Process-Time"] = str(duration) return response

Add it the same way:

python
app.add_middleware(TimingMiddleware)

BaseHTTPMiddleware is convenient when you need to read the request body or modify the response. For direct control over the raw ASGI interface—for example, to avoid response buffering or to handle non-HTTP scopes—implement a pure ASGI middleware from scratch.

Middleware Execution Order

The order of add_middleware calls matters, but it is not the intuitive order. In Starlette, the last middleware added is placed on the outside of the stack: it receives the request first and receives the response last. The first middleware added is closer to the route handler.

python
app.add_middleware(CORSMiddleware, ...) # added first: runs closer to the route app.add_middleware(TimingMiddleware) # added second: runs outermost

With this setup, TimingMiddleware sees the request before CORS processes it and sees the response after CORS has added headers. If you need to log the CORS headers, place your logging middleware outside CORS by adding it last. This ordering also determines what headers are visible and how exceptions propagate.

Async Handling and Streaming

BaseHTTPMiddleware.dispatch is an async method, so avoid blocking calls directly inside it. If you need to run blocking I/O or CPU-heavy work, offload it to a thread pool, for example with starlette.concurrency.run_in_threadpool, or use an async I/O library. A more important limitation is that BaseHTTPMiddleware can buffer the response body, which affects streaming responses. For streaming or WebSocket endpoints, use a pure ASGI middleware that works directly with send.

Here is a pure ASGI middleware that adds a header without buffering:

python
class HeaderMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] != "http": await self.app(scope, receive, send) return async def send_wrapper(message): if message["type"] == "http.response.start": message.setdefault("headers", []).append((b"X-Custom", b"value")) await send(message) await self.app(scope, receive, send_wrapper)

Use this pattern when you need to preserve streaming behavior or handle non-HTTP scopes like WebSockets.

Common Pitfalls and Production Considerations

One frequent mistake is combining allow_origins=["*"] with allow_credentials=True. The CORS specification does not allow a wildcard origin with credentialed requests, so list explicit origins when credentials are involved.

Middleware order also affects exception handling. An outer middleware can catch exceptions from downstream middleware or route handlers by wrapping call_next in try/except; an inner middleware cannot catch exceptions raised outside it. If a route handler raises an unhandled exception, the exception propagates outward through the middleware stack.

In production, keep middleware lean. Reading an entire request body with await request.body() can be expensive for large payloads. If you only need headers or want to avoid response buffering, use a pure ASGI middleware. Also filter out preflight OPTIONS requests early if your custom middleware does expensive work.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.