Middleware hooks into Django's request/response cycle—processing every request before it reaches a view and every response on the way out. Security, sessions, CSRF, and authentication rely on middleware.
Request/response flow
- Request enters middleware stack (top to bottom in MIDDLEWARE setting)
- URL resolver finds the view
- View returns HttpResponse
- Response passes back through middleware (bottom to top)
Built-in examples
SecurityMiddleware— security headers, HTTPS redirectSessionMiddleware— attaches session to requestAuthenticationMiddleware— sets request.userCorsMiddleware— third-party, for API CORS headers
Important interview questions and answers
- Q: Middleware order matters?
A: Yes—AuthenticationMiddleware must run after SessionMiddleware; CSRF before views that accept POST. - Q: Custom middleware use cases?
A: Request logging, tenant detection, maintenance mode, adding headers. - Q: process_view hook?
A: Runs after URL resolve, before view—can short-circuit with a response.
Self-check
- Which middleware sets request.user?
- Why does MIDDLEWARE order matter?
Tip: SessionMiddleware must appear before AuthenticationMiddleware in MIDDLEWARE—order is not alphabetical, it is dependency order.
Interview prep
- Middleware order?
Order matters—SessionMiddleware before AuthenticationMiddleware; CSRF before views accepting POST.