How does Django handle sessions and cookies?
Learn how Django manages sessions and cookies: server-side storage, the session key cookie, SessionMiddleware, backends, signed cookies and security flags.
Expected Interview Answer
Django stores per-user data server-side in a session and gives the browser only a signed cookie holding an opaque session key, so the sensitive data never leaves the server while requests stay linked to the right user.
SessionMiddleware manages the lifecycle: on a request it reads the sessionid cookie, loads the matching record from the configured backend (database, cache, cached_db, file, or signed cookie), and exposes it as request.session — a dict-like object. Any changes are saved at the end of the request, and a fresh Set-Cookie is sent when needed. Cookies themselves are small key-value pairs Django sets on the response; they can be signed with set_signed_cookie to detect tampering. Settings like SESSION_ENGINE, SESSION_COOKIE_AGE, SESSION_COOKIE_HTTPONLY, and SESSION_COOKIE_SECURE control storage and security.
- Sensitive data stays server-side; only an opaque key is in the cookie
- Pluggable backends: database, cache, cached_db, file, or cookie
- request.session behaves like a dict for easy reads and writes
- Cookies can be signed to detect tampering
- Security flags (HttpOnly, Secure, SameSite) harden the session cookie
AI Mentor Explanation
A session is the dressing-room locker holding all of a player's kit and notes, kept safely inside the pavilion. The cookie is just the small numbered tag the player carries — it proves which locker is theirs but holds nothing valuable. Lose the tag and you lose access, yet the kit itself never left the secure room.
Step-by-Step Explanation
Step 1
First response sets a cookie
When session data is written, Django saves a server-side record and sends a Set-Cookie with the opaque sessionid.
Step 2
Browser returns the cookie
On each later request the browser sends the sessionid cookie back automatically.
Step 3
Middleware loads the session
SessionMiddleware reads the key, loads the record from SESSION_ENGINE, and exposes request.session.
Step 4
Read and write session data
Views treat request.session like a dict; modifications are marked and saved before the response.
Step 5
Persist and secure
Django writes changes to the backend and applies flags like HttpOnly, Secure, and SameSite to the cookie.
What Interviewer Expects
- Session data lives server-side; cookie holds only a key
- Knows SessionMiddleware manages request.session
- Can name backends (db, cache, cached_db, file, signed cookie)
- Mentions security flags: HttpOnly, Secure, SameSite
- Understands signed cookies and tamper detection
Common Mistakes
- Thinking full session data is stored in the browser cookie
- Ignoring HttpOnly/Secure flags and exposing the session cookie
- Confusing signed cookies with encrypted cookies
- Forgetting to modify request.session so changes are not saved
Best Answer (HR Friendly)
“Django keeps each user's data on the server and gives the browser only a small ID inside a cookie that links back to it. On every request that cookie tells Django which user's data to load, and security flags stop the cookie from being read or stolen easily.”
Code Example
# Reading and writing session data
def add_to_cart(request, product_id):
cart = request.session.get('cart', [])
cart.append(product_id)
request.session['cart'] = cart # marks the session as modified
return redirect('cart')
def view_cart(request):
cart = request.session.get('cart', [])
return render(request, 'cart.html', {'cart': cart})
# A tamper-evident signed cookie on the response
def set_pref(request):
response = redirect('home')
response.set_signed_cookie('theme', 'dark', max_age=604800)
return responseFollow-up Questions
- What are the different SESSION_ENGINE backends and their trade-offs?
- What is the difference between a signed cookie and an encrypted one?
- How do HttpOnly, Secure, and SameSite protect the session cookie?
- When should you call request.session.set_expiry()?
- How does the cached_db backend improve performance?
MCQ Practice
1. Where is the actual session data stored by default?
By default Django stores session data server-side (e.g., the database) and puts only the session key in the cookie.
2. Which middleware exposes request.session?
SessionMiddleware loads the session record and attaches it as request.session on each request.
3. What does set_signed_cookie protect against?
A signed cookie is not encrypted but is tamper-evident: Django rejects the value if its signature does not verify.
Flash Cards
What does the session cookie contain? — Only an opaque session key; the real data stays server-side.
What manages request.session? — SessionMiddleware — it loads, exposes, and saves the session each request.
Signed vs encrypted cookie? — Signed cookies are readable but tamper-evident; they are not encrypted.
Which flags harden the session cookie? — HttpOnly, Secure, and SameSite (via SESSION_COOKIE_* settings).