Skip to main content
Middleware allows you to process requests before they reach your path operations and responses before they’re returned to the client. FastAPI provides multiple ways to implement middleware for different use cases.

Middleware Decorator

The simplest way to create middleware is using the @app.middleware("http") decorator:
The middleware function receives the request and a call_next function that will pass the request to the corresponding path operation, then return the response.

How It Works

  1. The middleware receives the incoming request
  2. You can perform operations before calling call_next
  3. Call await call_next(request) to pass the request to the path operation
  4. The path operation returns a response
  5. You can modify the response before returning it
  6. Return the response

Common Use Cases

Logging Requests

Adding Custom Headers

Request Modification

Built-in Middleware

FastAPI includes several pre-built middleware classes:

HTTPSRedirectMiddleware

Redirects all HTTP requests to HTTPS:

TrustedHostMiddleware

Enforces that all requests have a valid Host header:
Always configure TrustedHostMiddleware when deploying to production to prevent HTTP Host header attacks.

GZipMiddleware

Compresses responses for clients that support gzip:

Advanced: ASGI Middleware

For more complex scenarios, you can create pure ASGI middleware:
Use the @app.middleware("http") decorator for most use cases. Only create ASGI middleware when you need low-level access to the ASGI interface.

Middleware Execution Order

Middleware executes in the order it’s added:
The execution flow is:
  1. FirstMiddleware (in)
  2. SecondMiddleware (in)
  3. ThirdMiddleware (in)
  4. custom_middleware (in)
  5. Path operation
  6. custom_middleware (out)
  7. ThirdMiddleware (out)
  8. SecondMiddleware (out)
  9. FirstMiddleware (out)

Best Practices

  • Keep middleware focused on cross-cutting concerns (logging, auth, timing)
  • Avoid heavy computation in middleware
  • Always call await call_next(request) to ensure the request is processed
  • Handle exceptions appropriately to prevent breaking the request/response cycle
  • Order middleware carefully based on dependencies

Exception Handling in Middleware

See Also