Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 77 ยท Authentication and Security

Sessions and Cookies

Understand Django sessions and cookies: how request.session works, the session backends, signed cookies, cookie attributes and the settings that keep sessions safe.

HTTP has no memory. Every request arrives as a stranger, so a site that wants to remember a visitor (their login, the items in a cart, a language choice) must give the browser something to carry back. That something is a cookie, and the server-side storage it points to is a session.

Django handles both. In this lesson you will use request.session like a dictionary, see what really gets stored and where, choose between the session backends, set and read plain and signed cookies, and learn the cookie attributes and settings that protect your users. The live examples drive a real session middleware with the test client.

Cookies versus sessions

A cookie is a small piece of text the server asks the browser to keep (Set-Cookie) and send back on later requests (Cookie). Its content lives on the user's machine, so the user can read it, edit it or delete it.

A session moves the data to the server. The browser only receives a long random identifier in a cookie (named sessionid by default), and Django looks the data up under that id. The user cannot change what is stored, because they never see it.

sequenceDiagram
    participant B as Browser
    participant D as Django
    participant S as Session store
    B->>D: first request, no cookie
    D->>S: create session, save visits=1
    D-->>B: Set-Cookie: sessionid=abc123
    B->>D: next request, Cookie: sessionid=abc123
    D->>S: load abc123
    S-->>D: visits=1
    D-->>B: response (visits now 2)

The cookie carries only an id; the data stays on the server and is loaded by the session middleware on every request.

Using request.session

With SessionMiddleware enabled, every request has request.session, which behaves like a dictionary: read with get(), write with item assignment, delete with del or pop(). Values must be JSON-serializable (numbers, strings, lists, dicts, booleans, None), because Django serializes sessions as JSON. Do not store model instances; store their primary keys.

Django saves the session at the end of the request only if it was modified. Assigning a key counts. Changing a mutable value inside the session (appending to a list that is already stored) does not, so reassign the key or set request.session.modified = True.

Useful methods:

Call Effect
session.set_expiry(300) Expire after 300 seconds of inactivity. 0 means when the browser closes
session.cycle_key() New session id, same data (Django does this at login)
session.flush() Delete the data and the cookie (this is what logout does)
session.get_expiry_age() Seconds until expiry
Python A visit counter and a cart in request.session

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 browser sent only an id, yet the counter climbed because Django loaded the stored data each time. The data sits in the django_session table as an encoded blob, and get_decoded() shows what your code put in. Each Client is a separate browser, so two clients never share a session.

Session backends

SESSION_ENGINE decides where the data lives:

Backend Where the data is Notes
db (default) django_session table Simple and durable; one query per request that touches the session
cache Your cache (e.g. Redis) Fast, but data vanishes if the cache is cleared
cached_db Cache with a database fallback Fast reads and durable writes; a good production default
file Files on the server Rarely the best choice on multi-server setups
signed_cookies Inside the cookie itself No server storage, but the data goes to the browser

Expired rows in the db backend are not deleted automatically. Run manage.py clearsessions regularly (a cron job or scheduled task).

With signed_cookies the data is signed, not encrypted. The user cannot change it without detection, but they can read it, and the cookie is limited to about 4 KB. A replayed old cookie also stays valid until it expires, so it cannot be revoked server side. Never put secrets in it.

Plain and signed cookies

For small preferences that need no server storage (a theme, a dismissed banner) set a cookie directly on the response:

  • response.set_cookie(name, value, max_age=..., secure=..., httponly=..., samesite=...)
  • response.delete_cookie(name)
  • request.COOKIES reads incoming cookies as a plain dictionary of strings.

If tampering would matter, use response.set_signed_cookie(name, value, salt=...) and request.get_signed_cookie(name, default=..., salt=...). Django attaches a signature made with SECRET_KEY. When a client changes the value, get_signed_cookie raises BadSignature, or returns your default if you pass one.

Python Cookie attributes, signed cookies and the signed_cookies backend

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 theme cookie is readable by JavaScript (httponly=False) because a script might want to apply it. The plan cookie is not, and a forged value is rejected, falling back to the default. The last lines show the weakness of the signed-cookie backend: anyone can decode the payload.

These settings matter most in production:

Setting Recommended Why
SESSION_COOKIE_SECURE True Send the cookie only over HTTPS
SESSION_COOKIE_HTTPONLY True (default) JavaScript cannot read the cookie, so XSS cannot steal it
SESSION_COOKIE_SAMESITE "Lax" (default) or "Strict" Limits cross-site sending, a defense layer against CSRF
SESSION_COOKIE_AGE Your policy (default two weeks) How long a session lives
SESSION_EXPIRE_AT_BROWSER_CLOSE Optional Session cookie vanishes when the browser closes
SESSION_SAVE_EVERY_REQUEST Optional Slide the expiry on every request
CSRF_COOKIE_SECURE True Same idea for the CSRF cookie

Practical habits that keep sessions safe: let Django rotate the key at login (login() does it), call logout() or flush() when users sign out, keep sessions short for sensitive sites, store identifiers instead of whole objects, and never put anything in a session that you would not want the user to see if you ever switch to the signed_cookies backend. Changing SECRET_KEY invalidates signed cookies and, depending on settings, existing sessions, so treat it as a secret and rotate it deliberately (see Security in Django).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the browser store when you use Django's default session backend?

    The default db backend keeps the data in the django_session table and sends the browser only the id (sessionid cookie). The user cannot read or change the stored data.
  2. 2. You append to a list that is already stored in request.session['cart'] and nothing is saved. Why?

    Django saves the session only when it knows it changed. Assigning the key again, or setting request.session.modified = True, tells it so.
  3. 3. What is the main drawback of SESSION_ENGINE = 'signed_cookies'?

    Signing prevents tampering but not reading. The payload is also limited to about 4 KB and cannot be revoked server side before it expires.
  4. 4. What does HttpOnly do for a session cookie?

    HttpOnly prevents document.cookie from exposing the cookie. Secure restricts it to HTTPS and SameSite limits cross-site sending.

Summary

  • A cookie lives in the browser; a session keeps the data on the server and uses a cookie only for the id.
  • request.session acts like a JSON-serializable dictionary; reassign mutated values or set modified = True.
  • Choose a backend with SESSION_ENGINE: db, cache, cached_db, file or signed_cookies; run clearsessions for the database backend.
  • Use set_cookie for harmless preferences and set_signed_cookie when tampering matters; signing is not encryption.
  • Set SESSION_COOKIE_SECURE, keep HTTPONLY and a sensible SAMESITE, and rotate the session at login.
  • Store ids rather than objects, and never keep secrets in cookie-based storage.

Next up: Security in Django.