What is middleware in Django, and how would you write your own?
Middleware is a chain of hooks that wraps every request and response. Each one receives the request, may act on it, calls the next layer, and then may act on the response coming back.
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response # runs once at startup
def __call__(self, request):
start = time.monotonic()
response = self.get_response(request) # everything below runs here
response['X-Duration-Ms'] = f"{(time.monotonic() - start) * 1000:.1f}"
return responseAdd the dotted path to MIDDLEWARE in settings.
The rules:
- Order matters, and it is asymmetric. Requests pass through the list top to bottom; responses come back bottom to top.
- Returning a response without calling
get_responseshort-circuits everything below — which is exactly how authentication redirects and rate limiters work. - Placement has consequences.
SessionMiddlewaremust come beforeAuthenticationMiddleware, because authentication reads the session.
Note: Good uses are cross-cutting concerns: request logging, correlation ids, timing, locale, and enforcing a maintenance mode. Business logic does not belong here, because it runs on every single request including static files and health checks.





