Full answer
Think of middleware as a stack of wrappers around the view. Each entry in settings.MIDDLEWARE receives the request on the way in and the response on the way out.
The modern form is a factory that returns a callable:
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response # runs once at startup
def __call__(self, request):
start = time.perf_counter() # before the view
response = self.get_response(request)
response["X-Elapsed-ms"] = ... # after the view
return responseOrder rules:
- On the way in, middleware runs top to bottom. On the way out, bottom to top.
- If a middleware returns a response without calling
get_response, the layers below and the view are skipped, but the layers above still process the response. - Built-in order matters:
SessionMiddlewaremust come beforeAuthenticationMiddleware, which needs the session to findrequest.user.
Optional hooks on the class:
process_view(request, view_func, view_args, view_kwargs): runs just before the view, after URL resolution.process_exception(request, exception): runs when the view raises; return a response to handle it.process_template_response(request, response): for responses with.render().
Typical uses: request IDs and logging, timing, adding security headers, maintenance mode, tenant detection from the host.
Async support: middleware can declare sync_capable / async_capable. In an ASGI deployment, a sync-only middleware forces Django to switch threads around it, which costs performance. For new middleware in async projects, support both modes (Django provides @sync_and_async_middleware).
Keep middleware cheap; it runs on every request, including static checks and health probes.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import time
from django.http import HttpResponse, JsonResponse
from django.test import Client
from django.urls import path
class RequestIdMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.counter = 0
def __call__(self, request):
self.counter += 1
request.request_id = f"req-{self.counter}"
response = self.get_response(request)
response["X-Request-ID"] = request.request_id
return response
class MaintenanceMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path.startswith("/fees/") and settings.FEES_LOCKED:
return JsonResponse({"detail": "Fee payments are paused"}, status=503)
return self.get_response(request)
def process_exception(self, request, exception):
return JsonResponse({"detail": "Something went wrong", "id": request.request_id}, status=500)
def fees(request):
return HttpResponse("pay here")
def broken(request):
raise ValueError("boom")
urlpatterns = [path("fees/", fees), path("broken/", broken)]
settings.ROOT_URLCONF = __name__
settings.FEES_LOCKED = False
settings.MIDDLEWARE = [f"{__name__}.RequestIdMiddleware", f"{__name__}.MaintenanceMiddleware"]
c = Client()
r = c.get("/fees/")
print(r.status_code, r["X-Request-ID"], r.content.decode())
settings.FEES_LOCKED = True
r = c.get("/fees/")
print(r.status_code, r["X-Request-ID"], r.json())
r = c.get("/broken/")
print(r.status_code, r.json())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The counter on self is fine for a demo; in production use a UUID per request because instances are shared across threads. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 req-1 pay here 503 req-2 {'detail': 'Fee payments are paused'} 500 {'detail': 'Something went wrong', 'id': 'req-3'}
Key points
- Middleware wraps every request and response
- __init__ runs once; __call__ runs per request
- Requests go top to bottom, responses bottom to top
- Returning early skips the view and lower layers
- Sync-only middleware slows ASGI apps
Common mistakes
- Doing heavy work such as database queries in middleware on every request
- Placing middleware in the wrong order, for example auth before sessions
- Keeping per-request state on self (it is shared across requests and threads)
- Writing sync-only middleware for an ASGI project
Follow-ups
- How would you add a correlation ID that also appears in logs?
- What is the difference between middleware and a view decorator?
- How does Django handle sync middleware under ASGI?
Tips
- Draw the onion: in top to bottom, out bottom to top
- Show the __init__ vs __call__ difference
- Name a real use case such as request IDs or security headers