Middleware (Django)
Middleware in Django is a layer of hooks that process every request and response as they pass through the framework. Listed in the MIDDLEWARE setting, each one can inspect, modify, or short-circuit the request/response flow.
Django
Middleware wraps your views to handle cross-cutting concerns globally. Django ships several: SecurityMiddleware (security headers), SessionMiddleware (loads the session), AuthenticationMiddleware (sets request.user), CsrfViewMiddleware (CSRF checks), and more. They run top-to-bottom on the way in and bottom-to-top on the way out.
A middleware is a callable that gets the next handler and returns a function taking the request; it can do work before calling the next handler (request phase) and after (response phase). It can also return a response early to skip the view entirely, which is how authentication and redirects work globally.
Order in the MIDDLEWARE list matters because each wraps the next — for instance, AuthenticationMiddleware must come after SessionMiddleware because it relies on the session. Write custom middleware for app-wide concerns like request timing, locale, or maintenance mode.
Syntax
MIDDLEWARE = ["...SecurityMiddleware", "...SessionMiddleware", ...]Examples
Python
# simple timing middleware
import time
def timing_middleware(get_response):
def middleware(request):
start = time.time()
response = get_response(request)
response["X-Elapsed"] = f"{time.time() - start:.3f}s"
return response
return middleware