Django Middleware — The Onion Structure Wrapping Requests/Responses
Why MIDDLEWARE order matters and how chaining works internally
Requests enter: Security → Session → Common → Auth → View
Responses exit: View → Auth → Common → Session → Security
Like peeling an onion going in, wrapping it back going out.
Internal Implementation
get_response is the next link in the chain. Django iterates MIDDLEWARE list in reverse at startup, connecting each middleware's get_response to the next.
Why Order Matters
SessionMiddleware must precede AuthenticationMiddleware — Auth reads user info from session. Swap them and request.user is always Anonymous.
Key Points
MIDDLEWARE list order = request processing order (chained in reverse)
get_response(request) call executes next middleware/View
Request: outside→in, Response: inside→out (onion structure)
Session must come before Auth for request.user to work