Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 77 ยท Middleware, Signals and Internals

Middleware

Learn how Django middleware wraps every request: function and class middleware, execution order, process_view, exception handling and a timing example.

Middleware is code that sits between the web server and your views. Every request passes through a stack of middleware on the way in, and every response passes back through the same stack on the way out. Because the code runs for every request, middleware is the right place for work that should apply to the whole site: attaching a header, checking a setting, logging, rejecting bad requests early, or measuring how long a page took.

You have already been using middleware without writing any. Sessions, CSRF protection, authentication and security headers are all middleware that ship with Django. This lesson shows how the stack works, how to write your own, and how to avoid the classic ordering mistakes. If you have not read how a request travels through Django, the request and response cycle lesson is a good warm-up.

The onion model

Picture an onion. The view is the core. Each middleware is a layer around it. A request enters the outermost layer, passes inward through each layer, reaches the view, and then the response travels outward through the same layers in reverse order.

flowchart LR
    R["Request"] --> A["Middleware 1<br/>(first in the list)"]
    A --> B["Middleware 2"]
    B --> V["View"]
    V --> B2["Middleware 2<br/>(after the view)"]
    B2 --> A2["Middleware 1<br/>(after the view)"]
    A2 --> S["Response"]

The first middleware in the list is the outermost layer: it sees the request first and the response last.

The list lives in the MIDDLEWARE setting. Order matters because each layer can only rely on what the layers above it have already done. For example, the authentication middleware needs the session middleware above it, because it reads the user id from the session.

Writing middleware as a function

The simplest middleware is a function that takes get_response and returns another function that takes a request. get_response is "the rest of the stack": calling it runs every inner layer and the view, and gives you the response.

Python
def simple_middleware(get_response):
    # One-time setup, runs when the server starts.

    def middleware(request):
        # Code here runs BEFORE the view (and inner middleware).
        response = get_response(request)
        # Code here runs AFTER the view.
        return response

    return middleware

You can also write the same thing as a class with __init__ and __call__. Both styles are equivalent; the class style is handy when you keep state or want extra hook methods (you will meet them below).

The next example registers one function middleware and one class middleware, and records every step in a list so you can see the onion in action.

Python Middleware order: in and out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the two blocks of output. The "built at startup" lines appear only in the first request, because Django builds the whole chain once and reuses it. (It builds from the inside out, which is why Inner is built before outer.) The setup code in __init__ (or the outer function) is the place for expensive one-time work, such as compiling a regular expression or reading a setting. During each request, Inner runs inside outer, and the "after" lines come out in the opposite order to the "before" lines.

Middleware instances are shared by every request, and a production server may handle several requests at the same time. Never store per-request data on self. Put it on the request object instead, as the next example does.

Short-circuiting

A middleware does not have to call get_response. If it returns a response by itself, the inner layers and the view never run. This is how Django's CommonMiddleware redirects to the right URL, and how a middleware can block a request early.

Python
def require_api_key(get_response):
    def middleware(request):
        if request.path.startswith("/api/") and request.headers.get("X-Api-Key") != "secret":
            return HttpResponse("Missing or wrong API key", status=401)
        return get_response(request)

    return middleware

The response still travels back through the outer layers, so their "after" code runs even for blocked requests.

The extra hooks of class-based middleware

A class can define optional methods that Django calls at specific moments, in addition to __call__:

Hook When it runs Return value
process_view(request, view_func, view_args, view_kwargs) After the URL is resolved, just before the view runs None to continue, or a response to skip the view
process_exception(request, exception) When the view raises an exception None to let Django handle it, or a response
process_template_response(request, response) When the view returns an object with a render() method (such as TemplateResponse) The response to use

process_view is useful because, unlike __call__, it already knows which view was matched. The next example uses all of this together: a request-id middleware, a timing header (with a fake clock so the output is deterministic), a process_view guard and a process_exception that turns crashes into JSON.

Python process_view and process_exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check how each piece behaves. The guard never touched the home page. For /reports/ it returned 403 from process_view, so the view body did not run, yet the outer layers still added the request id and the elapsed-time header. The broken view raised ValueError, process_exception returned a JSON response instead, and the test client received a normal 500 answer rather than an exception. The "elapsed" value is always the same here because the fake clock advances by 5 each call; in real code you would use time.perf_counter().

Where Django's own middleware sits

A fresh project lists about seven middleware. The default order is deliberate:

Python
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",
]

SecurityMiddleware goes first so security headers and HTTPS redirects apply to everything. SessionMiddleware must come before AuthenticationMiddleware and MessageMiddleware, because both read the session. When you add your own middleware, ask what it depends on and put it below that, and ask who depends on it and put it above them. A middleware that needs request.user belongs below AuthenticationMiddleware.

Built-in middleware worth knowing

Beyond the default seven, Django ships a few middleware you opt into.

  • GZipMiddleware compresses responses for clients that send Accept-Encoding: gzip, and adds Vary: Accept-Encoding. Small bodies are left alone. Put it near the top of the list so it compresses what the other layers produce. Behind a CDN or nginx you usually compress there instead. Compressing pages that mix secrets with attacker-controlled text can leak data (the BREACH attack), so think twice for such pages.
  • ConditionalGetMiddleware adds an ETag to responses that lack one and answers matching If-None-Match requests with an empty 304 Not Modified. The view still runs; only the transfer is saved.
  • LocaleMiddleware picks the language per request (internationalization).
  • CommonMiddleware, SecurityMiddleware and CsrfViewMiddleware are part of the default list above. Django itself does not serve static files through middleware in production; WhiteNoise or your web server does.

Old-style middleware used separate hooks instead of one callable. django.utils.deprecation.MiddlewareMixin still lets you write it that way: it turns process_request and process_response methods into the modern interface, which is what third-party packages written for old Django often use.

Python GZip, ETag and MiddlewareMixin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 5,000-byte page shrank to about a hundred bytes because it repeats the same markup, the two-byte page was left uncompressed, and the second request with the stored ETag got a 304 with no body. For new code prefer the function or class style from earlier in this lesson, and use the mixin only to adapt old code.

Tips for good middleware

  • Keep it cheap. It runs on every request, including static-file and health-check URLs. A slow middleware slows the whole site.
  • Do one job. Several small middleware are easier to reorder and test than one large one.
  • Prefer a decorator for a few views. If only three views need the behavior, a view decorator is clearer than middleware with path checks. See function-based views for decorators.
  • Test with the test client. As the examples show, Client().get(...) runs the entire stack in-process, so you can assert on headers and status codes. More in the testing lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Middleware A is listed before middleware B in MIDDLEWARE. In which order does the code AFTER the view run?

    Middleware forms an onion. The request goes in through A then B, and the response comes back out through B then A.
  2. 2. What happens if a middleware returns a response without calling get_response?

    Returning early is called short-circuiting. It is how middleware can block or redirect a request before the view runs.
  3. 3. Why should you store per-request data on the request object instead of on self in a middleware class?

    The middleware is created once. Data on self would leak between requests and break under concurrency.
  4. 4. Which hook gives you the matched view function before it runs?

    process_view runs after URL resolution, so it receives the view function and its arguments, and may return a response to skip the view.

Summary

  • Middleware wraps every request and response; the MIDDLEWARE list is an onion, first item outermost.
  • Write it as a function taking get_response, or as a class with __init__ and __call__.
  • Setup code runs once at startup; per-request data belongs on request, never on self.
  • Returning a response early short-circuits the stack.
  • Class middleware can add process_view, process_exception and process_template_response hooks.
  • Order matters: sessions before authentication, security first, and your own middleware after whatever it depends on.

Next lesson: Signals.