Middleware Architecture
Relevant source files
The following files were used as context for generating this wiki page:
Starlette's middleware architecture is designed around the ASGI (Asynchronous Server Gateway Interface) specification, promoting modularity and reusability. Middleware components are layered wrappers around an ASGI application, allowing developers to intercept and modify the request/response cycle. This architecture supports a variety of use cases, from handling cross-origin requests (CORS) to global error management and legacy WSGI integration.
The system relies on a "stack" approach where each middleware layer receives an application (the next layer in the stack) and returns a new ASGI application. When a request enters the system, it passes through these layers in the order they were defined, reaching the core application last, and then returning back through the layers as a response.
Middleware Components and Definition
The Middleware Class
The Middleware class serves as a configuration container. It stores a middleware factory (usually a class) along with the positional and keyword arguments required to initialize it. This allows Starlette to defer the actual instantiation of the middleware until the application's middleware stack is built.
Sources: starlette/middleware/init.py:21-40
Middleware Definition Table
| Component | Description | Source |
|---|---|---|
Middleware | A wrapper for a middleware class and its arguments. | starlette/middleware/init.py:21 |
_MiddlewareFactory | A Protocol defining the signature for middleware initialization. | starlette/middleware/init.py:17 |
BaseHTTPMiddleware | An abstract base class providing a higher-level dispatch interface for HTTP requests. | starlette/middleware/base.py:23 |
Middleware Stack Construction
In a Starlette application, the middleware stack is constructed using build_middleware_stack(). The framework automatically includes internal middleware for error handling, ensuring the stack is robust.
- ServerErrorMiddleware: Added as the outermost layer to catch any unhandled exceptions in the entire stack.
- User Middleware: The custom middleware defined by the developer.
- ExceptionMiddleware: Added as the innermost layer to handle standard exceptions (like
HTTPException) occurring within routing or endpoints.
The stack is built by iterating through the list of middleware in reverse order, wrapping the Router (the base app) in each layer.
Sources: starlette/applications.py:65-90
Execution Flow
When an ASGI request (scope, receive, send) is processed, it enters the middleware_stack. Each layer has the opportunity to inspect the scope, modify it, or intercept the receive and send channels.
BaseHTTPMiddleware Flow
BaseHTTPMiddleware simplifies the process for HTTP-specific logic by providing a dispatch method. It handles the complexities of managing the ASGI state and provides a Request object and a call_next function to the developer.
Sources: starlette/middleware/base.py:23-53
Specialized Middleware Implementation
CORS Middleware
CORSMiddleware manages Cross-Origin Resource Sharing. It intercepts OPTIONS requests for preflight checks and adds necessary headers to simple responses based on configured allowed origins, methods, and headers.
Sources: starlette/middleware/cors.py:16-150
Exception Handling
Starlette differentiates between global server errors and specific HTTP/WebSocket exceptions:
- ServerErrorMiddleware: Formats 500 responses. In
debugmode, it generates detailed HTML tracebacks. - ExceptionMiddleware: Maps specific exception types (like
HTTPException) to handler functions. It populatesscope["starlette.exception_handlers"]for use by thewrap_app_handling_exceptionsutility.
Sources: starlette/middleware/errors.py:112-162, starlette/middleware/exceptions.py:19-58
WSGI Compatibility
The WSGIMiddleware allows legacy WSGI applications to run within the Starlette ASGI stack. It builds a WSGI environment from the ASGI scope and request body, executes the WSGI application in a separate thread, and streams the output back as ASGI messages.
Sources: starlette/middleware/wsgi.py:110-153
Summary
The Starlette Middleware Architecture provides a highly structured yet flexible way to extend application functionality. By utilizing the ASGI protocol, it enables a chain of responsibility where specialized components like CORSMiddleware or ServerErrorMiddleware can operate independently. The construction of the stack ensures that critical error handling is always present while allowing developers to inject custom logic through the Middleware configuration or the BaseHTTPMiddleware helper class.