Understanding Django Middleware for Request and Response Processing

Understanding Django Middleware for Request and Response Processing

Django middleware sits between the server-facing handler and the view. It can inspect or modify a request before Django resolves it to a view, and inspect or modify the resulting response before it is returned. Each middleware receives a get_response callable representing the next layer in the chain.

class RequestTimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        started_at = time.perf_counter()

        response = self.get_response(request)

        response["X-Request-Duration"] = (
            f"{time.perf_counter() - started_at:.4f}"
        )
        return response

For an ordinary request, Django calls middleware in the order listed in MIDDLEWARE. Each layer can do work before calling get_response, then do more work after it returns. That produces an inward request path and an outward response path: the first middleware sees the request first and the response last.

request
  → middleware A before
    → middleware B before
      → view
    ← middleware B after
  ← middleware A after
response

A middleware layer can also return a response without calling get_response. This short-circuits the remaining request path, so the view and later middleware are not called for that request. Earlier middleware still gets the response as the call unwinds.

class MaintenanceModeMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if maintenance_is_enabled():
            return HttpResponse("Temporarily unavailable", status=503)

        return self.get_response(request)

This makes middleware appropriate for behavior that spans many views, such as authentication integration, request tracing, security headers, or response compression. Logic specific to one endpoint usually belongs in that view or in a component the view calls.

How middleware is ordered and invoked

The order in MIDDLEWARE is part of the application’s behavior, not merely a configuration detail. If one middleware expects another to have populated request.session, established request.user, or attached messages, its position must reflect that dependency.

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "myapp.middleware.RequestTimingMiddleware",
]

For example, AuthenticationMiddleware relies on session support, so SessionMiddleware must precede it. MessageMiddleware relies on both sessions and authentication, so it belongs after them. These dependencies are easiest to maintain when the list is kept explicit and reviewed whenever middleware is added or reordered.

The request path also includes Django’s view-resolution stage. Middleware in __call__ runs before and after the downstream handler, while optional hooks such as process_view run after URL resolution but before the selected view. A process_view hook can inspect the resolved view and its arguments, or return a response to prevent that view from running.

class ViewAuditMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_view(self, request, view_func, view_args, view_kwargs):
        request.audit_view_name = view_func.__name__
        return None

Middleware that implements response-phase hooks sees responses in the reverse of the configured order. In the same way, exception hooks are considered in reverse order when a view raises an exception. This is why a layer that adds a response header can observe responses produced deeper in the chain, including responses returned by a short-circuiting layer.

Django constructs the middleware chain when it initializes the handler, not anew for every request. Keep request-specific state on the request or in local variables; storing it on the middleware instance can leak data between concurrent requests. The instance is shared, while each invocation receives its own request.

Writing middleware with well-defined responsibilities

A middleware should own one cross-cutting policy with a clear boundary. Request tracing, security headers, and maintenance-mode checks have different inputs and failure modes; combining them in a single class makes configuration and testing less precise. A view-specific rule usually belongs closer to the view, where its dependencies and effects are visible.

For example, a request identifier middleware can assign a fresh identifier to each request and expose it to downstream code. It should not store the identifier on the middleware instance, which is shared across requests.

import uuid


class RequestIdMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.request_id = uuid.uuid4().hex
        return self.get_response(request)

Keep configuration in __init__ and request-specific values in local variables or on the request. Avoid mutable instance attributes for counters, cached request data, or “current” users; concurrent requests can otherwise overwrite one another’s state. If a value must be shared, use a concurrency-safe mechanism designed for that purpose.

Make a middleware’s effects explicit. A layer that adds a response header should do that consistently, while a layer that attaches request metadata should document the attribute it creates and the code that consumes it. This makes dependencies visible and prevents unrelated views from acquiring surprising behavior.

class RequestIdHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["X-Request-ID"] = request.request_id
        return response

These responsibilities can be composed as separate middleware when both are needed: one establishes request metadata, and another publishes it on the response. Their ordering then expresses the dependency directly. A middleware should also avoid doing work unrelated to its policy, such as querying application data on every request when only a small set of views needs that data.

Handling requests, responses, and exceptions

Request-side work belongs before the call to get_response; response-side work belongs after it. Keep the response path safe for every response type the application can produce. In particular, a response may be a redirect, an error response, or a streaming response, not just a rendered HTML page.

class ResponsePolicyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        response["X-Content-Type-Options"] = "nosniff"
        if response.status_code >= 500:
            response["Cache-Control"] = "no-store"

        return response

Headers are usually a safer response transformation than changing response.content. A streaming response may not have a content attribute at all; its body is produced later from streaming_content. If middleware must transform streamed data, it must preserve the streaming behavior and account for both synchronous and asynchronous iterators. Otherwise, leave the body untouched.

On the request path, avoid reading the request body merely to inspect it. Accessing request.body or parsing request.POST can consume or buffer data, which matters for large uploads and streaming request bodies. Prefer metadata already available on the request, such as the method, path, and headers, unless the middleware specifically owns body parsing.

Exceptions require a distinction between the view and the middleware chain. Django’s exception handling converts exceptions from downstream processing into HTTP responses at middleware boundaries. Consequently, a broad try/except around get_response is not a reliable way to catch exceptions raised by a view.

class FragileExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            return self.get_response(request)
        except Exception:
            # This generally will not handle an exception raised by the view.
            return HttpResponse("Request failed", status=500)

For exceptions raised by a view, Django provides the optional process_exception hook. Return a response to handle the exception; return None to let Django continue its exception handling. Keep this hook narrow: translating a known application exception is usually safer than hiding every failure behind a generic response.

class MissingRecordMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exception):
        if isinstance(exception, RecordUnavailable):
            return HttpResponse("Record unavailable", status=404)

        return None

process_exception runs only for exceptions raised during view processing, and middleware hooks are considered in reverse order. Exceptions raised by the middleware itself are handled by Django’s outer exception machinery rather than by that same middleware’s process_exception method.

If middleware must add information to an error response, it can inspect the response returned from get_response, just as it would inspect any other response. Avoid changing the status or replacing the body unless that behavior is part of the middleware’s defined policy.

Testing middleware behavior and interactions

Test a middleware’s contract at the smallest useful boundary. A direct unit test can supply a request and a downstream callable, then verify what the middleware passes through, changes, or prevents from reaching that callable.

from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase


class AddHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["X-Policy"] = "applied"
        return response


class AddHeaderMiddlewareTests(SimpleTestCase):
    def setUp(self):
        self.request = RequestFactory().get("/")

    def test_adds_header_to_downstream_response(self):
        downstream = HttpResponse("body")
        get_response = lambda request: downstream
        middleware = AddHeaderMiddleware(get_response)

        response = middleware(self.request)

        self.assertIs(response, downstream)
        self.assertEqual(response["X-Policy"], "applied")

When the downstream callable has observable behavior, use a mock or a small function rather than inferring that it was called from the returned response. This makes pass-through and short-circuit behavior explicit.

from unittest.mock import Mock

from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase


class MaintenanceMiddleware:
    def __init__(self, get_response, enabled):
        self.get_response = get_response
        self.enabled = enabled

    def __call__(self, request):
        if self.enabled:
            return HttpResponse("Unavailable", status=503)
        return self.get_response(request)


class MaintenanceMiddlewareTests(SimpleTestCase):
    def test_enabled_mode_does_not_call_downstream(self):
        get_response = Mock()
        middleware = MaintenanceMiddleware(get_response, enabled=True)

        response = middleware(RequestFactory().get("/"))

        self.assertEqual(response.status_code, 503)
        get_response.assert_not_called()

    def test_disabled_mode_passes_request_downstream(self):
        request = RequestFactory().get("/")
        expected = HttpResponse("OK")
        get_response = Mock(return_value=expected)
        middleware = MaintenanceMiddleware(get_response, enabled=False)

        response = middleware(request)

        self.assertIs(response, expected)
        get_response.assert_called_once_with(request)

A unit test of __call__ does not prove that Django loads the middleware, orders it correctly, or runs its hooks. Use Django’s test client for those properties. The client exercises the configured handler and middleware stack, so the test should run with the same relevant MIDDLEWARE settings as the application.

from django.test import TestCase


class RequestIdIntegrationTests(TestCase):
    def test_request_id_is_available_on_response(self):
        response = self.client.get("/health/")

        self.assertEqual(response.status_code, 200)
        self.assertIn("X-Request-ID", response)
        self.assertTrue(response["X-Request-ID"])

For middleware whose behavior depends on ordering, record events at both sides of the downstream call. The expected sequence captures the request path and response path, making an accidental reorder visible.

from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase


class RecorderMiddleware:
    def __init__(self, get_response, name, events):
        self.get_response = get_response
        self.name = name
        self.events = events

    def __call__(self, request):
        self.events.append(f"{self.name}: request")
        response = self.get_response(request)
        self.events.append(f"{self.name}: response")
        return response


class MiddlewareOrderTests(SimpleTestCase):
    def test_outer_layer_runs_first_and_finishes_last(self):
        events = []
        view = lambda request: HttpResponse("OK")
        inner = RecorderMiddleware(view, "inner", events)
        outer = RecorderMiddleware(inner, "outer", events)

        outer(RequestFactory().get("/"))

        self.assertEqual(
            events,
            [
                "outer: request",
                "inner: request",
                "inner: response",
                "outer: response",
            ],
        )

Test exception hooks separately from exception conversion. A direct test can verify that a hook handles a particular exception and declines unrelated ones; a client test can verify the configured application behavior for an exception raised during a request.

from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase


class KnownErrorMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exception):
        if isinstance(exception, LookupError):
            return HttpResponse("Not found", status=404)
        return None


class ExceptionHookTests(SimpleTestCase):
    def setUp(self):
        self.middleware = KnownErrorMiddleware(lambda request: None)
        self.request = RequestFactory().get("/")

    def test_handles_expected_exception(self):
        response = self.middleware.process_exception(
            self.request, LookupError("missing")
        )

        self.assertEqual(response.status_code, 404)

    def test_leaves_unrelated_exception_unhandled(self):
        response = self.middleware.process_exception(
            self.request, ValueError("invalid")
        )

        self.assertIsNone(response)

Keep tests independent of middleware instance state unless shared state is itself part of the contract. A fresh middleware instance per test helps expose accidental assumptions about request history, while tests using the client can catch behavior that only appears when the configured chain is assembled.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *