
When you're building a small API with FastAPI, handling requests and returning responses is usually straightforward. You create an endpoint, define a few models, connect a database, and you're ready to go.
But things get a little different when your application starts growing.
Suddenly, you need to log incoming requests, measure response times, handle cross-origin requests from your frontend, track errors, and troubleshoot slow endpoints. Adding the same logic to every route quickly becomes difficult to maintain.
For example, imagine you have 30 API endpoints. You want to record how long each request takes and log its HTTP status code. You could add timing and logging logic to every endpoint, but that would duplicate code and make future changes harder.
This is where FastAPI middleware becomes useful.
Middleware allows you to execute code around the request-response cycle without repeating that logic in every endpoint. You can inspect incoming requests, attach information to request state, modify responses, and perform cleanup after a response has been generated.
In this guide, we'll build custom middleware for request logging, response-time tracking, request IDs, and error handling. We'll also configure CORS properly and discuss some common mistakes that can cause problems in production.
1. What Is Middleware in FastAPI?
Middleware is a layer that sits between the client and your application's routes.
When a client sends an HTTP request, middleware can run before the request reaches your endpoint. After the application generates a response, middleware can also perform additional work before that response is returned to the client.
A simplified request flow looks like this:
Client
|
v
Request Logging Middleware
|
v
Request ID Middleware
|
v
FastAPI Application
|
v
API Endpoint
|
v
Response
|
v
Middleware Processing
|
v
ClientThis is a simplified illustration. When multiple middleware layers are registered, their ordering affects which layer receives the request first and which layer processes the response last.
Middleware is useful for functionality that applies across multiple endpoints, including:
Logging incoming requests and outgoing responses.
Measuring API response times.
Generating request IDs for debugging.
Adding security-related response headers.
Handling cross-origin resource sharing (CORS).
Collecting metrics for monitoring.
Recording request metadata for tracing.
However, middleware isn't the right place for every shared operation. Authentication and authorization, for example, are often better handled through FastAPI dependencies when they need to vary by route or depend on the current user.
The goal is to keep cross-cutting HTTP concerns separate from your business logic.
2. Setting Up a FastAPI Project
Before implementing middleware, let's create a small FastAPI application.
Create a project directory:
mkdir fastapi-middleware-demo
cd fastapi-middleware-demoCreate a virtual environment:
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateOn Windows, run:
venv\Scripts\activateInstall the required packages:
pip install fastapi uvicornCreate a file named main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Welcome to FastAPI"}
@app.get("/users")
async def get_users():
return {
"users": [
{"id": 1, "name": "Rahul"},
{"id": 2, "name": "Priya"},
]
}Start the development server:
uvicorn main:app --reloadOpen http://127.0.0.1:8000 in your browser. You should receive a JSON response.
Now we have a working application. Let's add middleware without changing the endpoint implementations.
3. Creating Custom Middleware with @app.middleware("http")
FastAPI provides a convenient decorator for writing HTTP middleware:
@app.middleware("http")
async def custom_middleware(request, call_next):
response = await call_next(request)
return responseThe middleware receives two arguments:
request: The incoming HTTP request.call_next: A callable that passes the request to the next middleware layer or the application.
Calling await call_next(request) allows the request to continue through the application. The resulting response can then be inspected or modified.
Let's create middleware that logs the HTTP method, URL path, and response status.
from fastapi import FastAPI, Request
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.middleware("http")
async def request_logging_middleware(
request: Request,
call_next
):
logger.info(
"Incoming request: %s %s",
request.method,
request.url.path
)
response = await call_next(request)
logger.info(
"Response status: %s",
response.status_code
)
return response
@app.get("/")
async def home():
return {"message": "Hello, FastAPI!"}When you call the / endpoint, your terminal should show messages similar to these:
INFO:__main__:Incoming request: GET /
INFO:__main__:Response status: 200The useful part is that this middleware applies to all relevant HTTP requests handled by the application. You don't need to add logging to every route.
What happens if an endpoint raises an exception?
A normal response allows the middleware to log its status code. However, if an unhandled exception escapes the application's inner processing, the middleware might not reach the response-logging statement.
You can use try/finally for cleanup and timing, or handle exceptions when you have a specific reason to do so.
Be careful about catching every exception and returning a generic response inside middleware. Doing so can bypass or interfere with FastAPI's normal exception-handling behavior, depending on where the middleware is installed.
For most applications, start with logging and use FastAPI's exception handlers for consistent API error responses.
4. Measuring API Response Time
Request logging tells us which endpoints are being called, but it doesn't tell us whether they're fast or slow.
Consider an endpoint that queries a database, calls an external service, and combines the results. If it takes three seconds to respond, we need a way to identify that delay.
Middleware can measure the elapsed time for each request.
Python's time.perf_counter() is a good choice for measuring elapsed durations.
import time
import logging
from fastapi import FastAPI, Request
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.middleware("http")
async def response_time_middleware(
request: Request,
call_next
):
start_time = time.perf_counter()
response = await call_next(request)
duration = time.perf_counter() - start_time
duration_ms = duration * 1000
logger.info(
"%s %s completed in %.2f ms",
request.method,
request.url.path,
duration_ms
)
response.headers["X-Process-Time"] = (
f"{duration_ms:.2f}ms"
)
return response
@app.get("/products")
async def get_products():
# Simulate a slow operation for demonstration.
import asyncio
await asyncio.sleep(0.5)
return {"products": ["Laptop", "Keyboard", "Mouse"]}Call the /products endpoint. You should see a log entry showing a duration of roughly 500 milliseconds, plus some additional processing overhead.
The response also contains a header similar to:
X-Process-Time: 501.23msThe exact value depends on your environment.
This header can be useful while debugging an API, especially when working with a React or Next.js frontend.
One important detail: this measurement represents the time spent awaiting the downstream application response through this middleware. It isn't necessarily the complete time experienced by the client. Network latency, reverse proxies, response transmission, and other infrastructure can add more time.
Also, call_next() timing is not a complete measurement of streaming response delivery. If you need precise measurements of response-body transmission, you'll need instrumentation that accounts for the ASGI response lifecycle.
For normal JSON APIs, this simple approach is often a useful starting point.
5. Adding Request IDs for Easier Debugging
Imagine a user reports that an API failed at 11:30 AM. Your logs contain thousands of requests, and you need to identify which log entries belong to that specific request.
Searching by URL alone might not be enough because hundreds of users could call the same endpoint at the same time.
A request ID solves this problem by assigning a unique identifier to each request.
You can use Python's uuid module to generate one.
import uuid
import logging
from fastapi import FastAPI, Request
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.middleware("http")
async def request_id_middleware(
request: Request,
call_next
):
request_id = str(uuid.uuid4())
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-ID"] = request_id
return response
@app.get("/orders")
async def get_orders(request: Request):
request_id = request.state.request_id
logger.info(
"Fetching orders for request %s",
request_id
)
return {
"request_id": request_id,
"orders": [
{"id": 101, "status": "processing"},
{"id": 102, "status": "shipped"}
]
}Every request now receives a different ID.
The request.state object allows middleware to attach data that can be accessed by downstream endpoints and dependencies during that request.
Should you trust a client-provided request ID?
Sometimes a reverse proxy or frontend already supplies a request ID. You may want to reuse it rather than generate a new one.
However, don't blindly trust arbitrary client-provided identifiers. Validate their format and length, and consider whether the application should generate its own internal ID while storing an upstream ID separately.
This matters because request IDs often appear in logs and monitoring systems. Unvalidated values can create confusing log entries or other operational problems.
In a production environment, request IDs become much more useful when they are included consistently in application logs, error reports, and distributed tracing data.
6. Combining Logging, Request IDs, and Response Timing
The previous examples demonstrate separate middleware implementations. In a real application, you may want to combine these features into one middleware.
This keeps related request-level logic together and avoids unnecessary duplication.
Here's a more complete example:
import logging
import time
import uuid
from fastapi import FastAPI, Request
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.middleware("http")
async def observability_middleware(
request: Request,
call_next
):
request_id = str(uuid.uuid4())
request.state.request_id = request_id
start_time = time.perf_counter()
try:
response = await call_next(request)
duration_ms = (
time.perf_counter() - start_time
) * 1000
response.headers["X-Request-ID"] = request_id
response.headers["X-Process-Time"] = (
f"{duration_ms:.2f}ms"
)
logger.info(
"request_id=%s method=%s path=%s "
"status=%s duration_ms=%.2f",
request_id,
request.method,
request.url.path,
response.status_code,
duration_ms
)
return response
except Exception:
duration_ms = (
time.perf_counter() - start_time
) * 1000
logger.exception(
"request_id=%s method=%s path=%s "
"failed after %.2f ms",
request_id,
request.method,
request.url.path,
duration_ms
)
raise
@app.get("/")
async def home(request: Request):
return {
"message": "API is running",
"request_id": request.state.request_id
}
@app.get("/error")
async def trigger_error():
raise RuntimeError("Example server error")The middleware now:
Generates a unique request ID.
Stores it in request state.
Measures elapsed processing time.
Logs the HTTP method, path, status, and duration.
Adds request ID and timing headers to normal responses.
Logs unhandled exceptions and re-raises them.
Notice that the exception is re-raised rather than converted into a custom JSON response. This allows the application's normal exception-handling machinery to process it.
There is one subtle limitation: when an exception escapes the middleware's call_next() call, the middleware cannot attach headers to the response that the framework or server may subsequently generate.
If you need request IDs on error responses as well, configure the appropriate exception handlers or use an outer ASGI middleware layer that can observe the final response.
7. Understanding CORS in FastAPI
CORS stands for Cross-Origin Resource Sharing.
It controls whether a browser allows frontend JavaScript running on one origin to access resources on another origin.
For example, suppose your frontend is running at:
https://myfrontend.comAnd your FastAPI backend is running at:
https://api.mybackend.comThese are different origins, even though both use HTTPS. Their hostnames differ.
If the frontend calls the backend using fetch() or Axios, the browser may block JavaScript from accessing the response unless the backend returns appropriate CORS headers.
This is not the same as server-side access control. CORS is enforced by browsers and should not be treated as a replacement for authentication or authorization.
Configuring CORS with CORSMiddleware
FastAPI provides CORS support through Starlette's CORSMiddleware.
You don't need to write custom CORS middleware for a typical application. Use the built-in implementation instead.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
allowed_origins = [
"http://localhost:3000",
"http://localhost:5173",
"https://myfrontend.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=[
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
],
allow_headers=[
"Authorization",
"Content-Type",
"X-Request-ID",
],
)Let's understand the important options.
allow_origins
This list contains the origins permitted to access your API from a browser.
Include the exact scheme, hostname, and port where applicable. For example, http://localhost:3000 and http://localhost:5173 are different origins.
allow_credentials
Set this to True if your browser-based application needs to send credentials such as cookies or HTTP authentication information as part of a cross-origin request.
When credentials are enabled, configure explicit allowed origins rather than using a wildcard origin.
allow_methods
This specifies which HTTP methods are allowed for cross-origin requests.
You should enable only the methods your frontend needs.
allow_headers
This specifies which request headers the browser is permitted to send. If your frontend sends a custom header such as X-Request-ID, make sure the CORS configuration permits it when required.
Why does the browser send an OPTIONS request?
You might notice that a browser sends an OPTIONS request before the actual API request.
This is called a CORS preflight request.
For example, a frontend request using an Authorization header or a non-simple HTTP method may trigger a preflight check. The browser asks the server whether the intended cross-origin request is permitted.
CORSMiddleware handles the preflight request and returns the appropriate CORS headers.
If the preflight fails, the browser might never send the actual request.
Common CORS mistakes
Mistake 1: Allowing every origin in production
This configuration is convenient during early development:
allow_origins=["*"]However, unrestricted origins are generally not appropriate for production applications, particularly when credentials are involved.
Specify the frontend domains you actually trust.
Mistake 2: Forgetting the port number
These origins are different:
http://localhost:3000
http://localhost:5173If your frontend runs on port 5173 but only port 3000 is allowed, the browser may reject the request.
Mistake 3: Assuming CORS protects your API
CORS does not stop direct HTTP requests made by scripts, command-line clients, or other servers. It primarily controls browser access to cross-origin responses.
Your API still needs proper authentication, authorization, input validation, and other security controls.
8. Adding Security Headers with Middleware
Middleware can also attach response headers that help browsers handle content more safely.
For example, you can add a few security-related headers:
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def security_headers_middleware(
request: Request,
call_next
):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Referrer-Policy"] = (
"strict-origin-when-cross-origin"
)
return responseThese headers have different purposes:
X-Content-Type-Options: nosnifftells browsers not to infer a different content type from the declared one.X-Frame-Options: DENYprevents the page from being displayed inside a frame.Referrer-Policycontrols how much referrer information the browser sends in relevant requests.
The framing policy is particularly relevant when your application serves HTML pages or interactive documentation. If you intentionally embed pages in an iframe, DENY may break that functionality.
For a production website, you may also need a carefully configured Content Security Policy (CSP), HTTPS, secure cookie settings, and other controls based on your application.
Avoid copying security headers without understanding their effects. A policy that is appropriate for one application can break another.
9. Understanding Middleware Order
Middleware order is one of the easiest things to overlook when an application grows.
Suppose you have request ID middleware, timing middleware, and CORS middleware. Each layer can affect what happens before and after a request reaches the application.
In FastAPI, middleware added with app.add_middleware() is organized as a stack. The last middleware added through this mechanism is the outermost user middleware, and it runs first for incoming requests. The response then travels back through the stack in the opposite direction.
Framework-level middleware and exception-handling layers can also affect the complete request lifecycle.
For example, CORS headers may need to be present even when an unhandled exception occurs. If CORS middleware sits inside a layer that generates the final error response, those headers might not appear on that response.
Starlette documents an approach for applications that need CORS headers on error responses: wrap the entire application with CORSMiddleware.
For example:
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
api = FastAPI()
@api.get("/")
async def home():
return {"message": "Hello"}
app = CORSMiddleware(
app=api,
allow_origins=["https://myfrontend.com"],
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type"],
)In this arrangement, run the exported app with your ASGI server. The outer CORS layer can process responses generated by the inner application, including applicable error responses.
The trade-off is that the exported ASGI application is now the middleware wrapper, while your FastAPI instance is named api. Account for that when configuring startup hooks, tests, and application imports.
The important lesson is to understand the middleware stack instead of assuming that every layer sees every response.
10. Middleware vs. FastAPI Dependencies
Middleware and dependencies can both help avoid duplicated code, but they solve different problems.
Consider an authentication requirement.
You might want every request to have a request ID. Middleware is a natural fit because request identification applies broadly across the application.
However, suppose only certain routes require an authenticated user. FastAPI dependencies are often a better choice.
For example:
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
async def get_current_user():
# Replace this with actual token validation.
user = {"id": 1, "name": "Manjeet"}
if not user:
raise HTTPException(
status_code=401,
detail="Authentication required"
)
return user
@app.get("/profile")
async def get_profile(
user=Depends(get_current_user)
):
return {"user": user}This example uses a placeholder rather than real authentication. A production implementation must validate credentials and derive the user identity from a trusted source.
Here's a simple comparison:
Requirement | Recommended approach |
|---|---|
Log HTTP requests | Middleware |
Measure request processing time | Middleware or observability instrumentation |
Generate request IDs | Middleware or tracing instrumentation |
Configure CORS |
|
Add common response headers | Middleware |
Validate a user's authentication token | Dependency or authentication middleware, depending on the architecture |
Check route-specific permissions | Dependencies or authorization policies |
Validate request body data | Pydantic models |
Reuse database sessions | Dependencies |
The key is to avoid putting all application logic into middleware just because middleware can run for every request.
11. Production Best Practices
Middleware is easy to add, but poorly designed middleware can create performance problems or expose sensitive information.
Here are some practices worth following.
Avoid logging sensitive data
Don't log authorization tokens, passwords, session cookies, or complete request bodies by default.
Even URL query parameters can contain sensitive information, such as reset tokens or personal data.
Log only the information you need for debugging and operational monitoring.
Keep middleware lightweight
Middleware executes across many requests. Expensive operations can affect the performance of your entire application.
Avoid making unnecessary external API calls or synchronous database queries inside middleware.
If you need to send logs to an external system, use a proper logging pipeline rather than waiting for a remote logging service on every request.
Use structured logging
For production applications, structured logs are generally more useful than arbitrary text.
For example, you might log fields such as:
request_id=abc123
method=GET
path=/products
status_code=200
duration_ms=42.8A structured logging library can emit these fields as JSON, making them easier to search and analyze in centralized logging systems.
Handle streaming responses carefully
Some responses are streamed instead of being returned as a complete JSON document.
Timing only the awaited call_next() operation may not capture the time needed to transmit the entire response body. Middleware that consumes or replaces a streaming response body can also break streaming behavior.
If your application handles large file downloads, server-sent events, or streaming AI responses, test middleware against those use cases explicitly.
Don't confuse process time with end-to-end latency
The duration measured inside middleware doesn't include every part of the request's journey.
A reverse proxy, network connection, TLS negotiation, load balancer, or client-side processing may add more time.
For production monitoring, combine application-level timing with infrastructure metrics and distributed tracing where appropriate.
Test middleware behavior
Test both successful and failing requests.
Verify that request IDs are present where expected, CORS preflight requests work, errors are logged, and middleware does not break streaming endpoints.
You should also test the actual deployment configuration because proxies and multiple middleware layers can change the behavior you observe locally.
12. Final Thoughts
FastAPI middleware is one of those features that becomes more valuable as your application grows. It lets you handle cross-cutting concerns in one place instead of repeating the same logic across every route.
In this guide, we covered custom middleware for request logging, response-time measurement, request IDs, and security headers. We also explored CORS configuration, middleware ordering, and the differences between middleware and dependency injection.
For a small API, a simple logging middleware and CORSMiddleware may be all you need. As your application grows, you can build on that foundation with structured logging, distributed tracing, and monitoring tools.
My recommendation is to start with three things: request IDs, request timing, and properly configured CORS. These features are relatively straightforward to implement and can make debugging a real production issue much easier.
Most importantly, keep middleware focused. It should help your application remain observable, secure, and maintainable without turning into a second place where business logic lives.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


