Django Middleware Explained: The Complete Guide with Real-World Examples
Learn how Django processes every request and response, and why middleware is one of the most powerful features in Django.
Introduction
When I started with Django, I focused on models, views, URLs and templates. Then I wondered: how does Django know a user is logged in? Who adds security headers to every response? Where are CSRF tokens checked? How could I log every request without touching every view?
The answer to all of these is middleware. Every request entering a Django application and every response leaving it passes through a chain of middleware components. Think of airport security: each checkpoint has one job, such as checking identity or scanning baggage, and every passenger passes through all of them before reaching the gate.
Middleware gives you one central place for logic that applies to every request: authentication, sessions, CSRF protection, logging, timing, security headers and IP restrictions. Without it, you would repeat that logic in every view. This guide covers the request lifecycle, Django’s built-in middleware, how to write your own, real-world examples, and the ordering rules that keep it all working.
Understanding the Django Request Lifecycle
When a user opens https://example.com/products/, the browser sends an HTTP request carrying the URL, method, headers, cookies, tokens and client IP. Here is what happens next:
- Middleware receives the request. Each component can inspect or modify it: load the session, identify the user, check the CSRF token, attach a request ID, or reject malicious traffic. A middleware can also return a response immediately, and then the view never runs.
- The URL resolver matches the path against
urlpatterns, for examplepath("products/", views.products). - The view runs your business logic: it reads input, queries the database through the ORM, calls services, and builds HTML or JSON.
- The response travels back through the same middleware in reverse. Each component can add security or cache headers, set cookies, compress content or log timing before the browser receives it.
Middleware runs twice per request, once on the way in and once on the way out. That is why it is described as the bridge between the client and your application. A login request shows each layer doing one job:
Built-in Django Middleware Explained
Django ships middleware for the problems every web application has. A new project’s settings.py enables them like this:
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",
]
Django runs them top to bottom on the request and bottom to top on the response.
SecurityMiddleware
Applies security settings to every request and response. With SECURE_SSL_REDIRECT = True it redirects HTTP to HTTPS, and with SECURE_HSTS_SECONDS set it sends the Strict-Transport-Security header so browsers stop trying plain HTTP. It also sends headers such as X-Content-Type-Options: nosniff and Referrer-Policy. For anything handling passwords or payments, this is your first line of defence.
SessionMiddleware
HTTP is stateless: each request arrives with no memory of the last one. SessionMiddleware lets Django remember data across requests, such as the logged-in user, a shopping cart, preferences or language. Without it, a user who logs in on one request is forgotten on the next.
CommonMiddleware
Handles URL normalisation and a few housekeeping tasks. With APPEND_SLASH on (the default), a request for /products that matches no pattern redirects to /products/. It can also block user agents listed in DISALLOWED_USER_AGENTS.
CsrfViewMiddleware
Protects against Cross-Site Request Forgery, where an attacker’s site submits a hidden form to your site using the victim’s logged-in session, for example to trigger a bank transfer. Django rejects unsafe requests such as POST that lack a valid token with 403 Forbidden. In templates, one tag adds the token:
<form method="post">
{% csrf_token %}
</form>
AuthenticationMiddleware
Identifies the current user from the session and attaches it as request.user, which every view can use:
def dashboard(request):
if request.user.is_authenticated:
return render(request, "dashboard.html")
MessageMiddleware
Enables one-time notifications such as “Profile updated” or “Item added to cart”. The message shows once, then disappears:
from django.contrib import messages
messages.success(request, "Profile updated successfully.")
XFrameOptionsMiddleware
Protects against clickjacking, where another site embeds your page in an invisible iframe and tricks users into clicking it. It sends X-Frame-Options: DENY by default, so browsers refuse to frame your pages.
| Middleware | Purpose |
|---|---|
SecurityMiddleware | HTTPS redirect, HSTS and security headers |
SessionMiddleware | Maintains user sessions |
CommonMiddleware | URL normalisation such as trailing slashes |
CsrfViewMiddleware | Protects against CSRF attacks |
AuthenticationMiddleware | Identifies logged-in users |
MessageMiddleware | Displays one-time messages |
XFrameOptionsMiddleware | Prevents clickjacking |
Building Your First Custom Middleware
Built-in middleware covers the common cases. When your application needs something on every request, such as logging, timing, request IDs, maintenance mode, IP restrictions or custom header checks, write it once as middleware instead of in every view.
Create middleware.py inside an app, for example blog/middleware.py. A middleware is a class with two methods:
class RequestLoggerMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f"Request: {request.method} {request.path}")
response = self.get_response(request)
return response
__init__(get_response)runs once, when Django loads the middleware chain. It stores the next callable in the chain.__call__(request)runs for every request. Code beforeself.get_response(request)sees the request on the way in; you can inspect it, modify it, attach attributes or block it.self.get_response(request)passes the request to the next middleware or the view. If you do not call it, the request stops here.- Code after it sees the response on the way out, where you can add headers, set cookies or log timing before returning it.
Register it in settings.py. Its position in the list decides when it runs:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"blog.middleware.RequestLoggerMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
...
]
A visit to /products/ now logs Request: GET /products/. You did not modify a single view.
Real-World Middleware Examples
1. Request logging and timing
A request log helps you debug issues, monitor traffic and audit activity. Adding the duration turns it into basic performance monitoring:
import logging
import time
logger = logging.getLogger(__name__)
class RequestLoggerMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.perf_counter()
response = self.get_response(request)
duration = time.perf_counter() - start
logger.info(
"%s %s %s %.3fs",
request.method,
request.path,
response.status_code,
duration,
)
return response
GET /products/ 200 0.042s POST /login/ 302 0.156s
2. Request ID
When many requests run at once, their log lines interleave. A unique ID per request lets you trace one request through every log line, and returning it in a header lets clients report it:
import uuid
class RequestIDMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.request_id = str(uuid.uuid4())
response = self.get_response(request)
response["X-Request-ID"] = request.request_id
return response
3. Maintenance mode
During maintenance, return a friendly 503 instead of stopping the server or showing errors. Reading the flag from settings lets you switch it without a code change:
from django.conf import settings
from django.http import HttpResponse
class MaintenanceMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if getattr(settings, "MAINTENANCE_MODE", False):
return HttpResponse("We'll be back soon!", status=503)
return self.get_response(request)
4. Simple rate limiter
This limits each IP address to 100 requests per minute using Django’s cache:
from django.core.cache import cache
from django.http import HttpResponse
class RateLimitMiddleware:
LIMIT = 100
WINDOW = 60 # seconds
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
ip = request.META.get("REMOTE_ADDR")
key = f"rate:{ip}"
# add() only sets the key if it is missing, so the window starts
# at the first request and is not extended by later ones
cache.add(key, 0, timeout=self.WINDOW)
try:
count = cache.incr(key)
except ValueError: # the key expired between add() and incr()
cache.set(key, 1, timeout=self.WINDOW)
count = 1
if count > self.LIMIT:
return HttpResponse("Too Many Requests", status=429)
return self.get_response(request)
With a shared cache such as Redis or Memcached, incr() is atomic, so concurrent requests cannot slip past the limit. Behind a proxy or load balancer, REMOTE_ADDR is the proxy’s address; read the client IP from the header your proxy sets, and only trust it from that proxy. For production, a maintained package or your API gateway is usually a better choice.
Middleware Execution Order & Best Practices
Django runs middleware in the exact order of the MIDDLEWARE list on the way in, and in reverse on the way out.
With Security, Session and a custom logger configured in that order:
Request phase
SecurityMiddleware ↓ SessionMiddleware ↓ RequestLoggerMiddleware ↓ View
Response phase
View ↓ RequestLoggerMiddleware ↓ SessionMiddleware ↓ SecurityMiddleware
Order matters because middleware depends on other middleware:
- Security first.
SecurityMiddlewaregoes near the top so every request is protected as early as possible. - Sessions before authentication.
AuthenticationMiddlewarereads the user from the session, soSessionMiddlewaremust come before it. - Custom middleware after its dependencies. If yours reads
request.user, place it afterAuthenticationMiddleware, or the attribute will not exist yet.
Correct order
SessionMiddleware ↓ AuthenticationMiddleware
Incorrect order
AuthenticationMiddleware ↓ SessionMiddleware
Middleware can also stop a request early, which skips the URL resolver and view entirely. Placed after AuthenticationMiddleware:
if not request.user.is_authenticated:
return HttpResponse("Unauthorized", status=401)
Best Practices
Middleware runs on every request. An extra 20 ms per request is 200 seconds of processing per 10,000 requests, so small costs add up.
Avoid
- Database queries such as
Product.objects.count(), which then run on every page - External API calls and large file operations
- Business logic such as orders, payments or reports; it belongs in views, services and models
- One middleware doing several unrelated jobs
- Middleware where a view decorator would cover the few views that need it
Instead
- Read headers, validate requests, attach metadata
- Keep each middleware to one responsibility
- Keep it stateless and cache data it reads often
- Use structured logging and handle exceptions
- Write unit tests and document each middleware’s purpose
Quick Checklist
Before deploying a custom middleware, check that it:
- Solves a problem that really applies to every request
- Has one clear responsibility
- Is lightweight and avoids unnecessary database queries
- Sits in the correct position in
MIDDLEWARE - Calls
get_response(request), unless it deliberately returns early - Has tests
Conclusion & Key Takeaways
Middleware runs before the view on every request and after it on every response, so it can inspect, modify or block traffic in both directions. Django’s built-in middleware handles security, sessions, CSRF, authentication, messages and clickjacking with almost no configuration. Custom middleware centralises cross-cutting concerns such as logging, timing, request IDs, maintenance mode and rate limiting, as long as it stays lightweight, focused and correctly ordered.
Start with the built-in stack, then add your own as requirements grow. These topics build naturally on middleware: