Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 72 ยท State: Sessions and Cookies

Sessions

Learn how Flask sessions keep per-user data in a signed cookie, why SECRET_KEY matters, how permanent sessions work and what you should never store in one.

A session is Flask's built-in way to remember things about one visitor between requests: who is logged in, what is in the cart, which step of a wizard they reached. You use it like a dictionary, session["user"] = "ada", and read it back on the next request.

Under the hood Flask puts that dictionary into a cookie, as you saw in Cookies, and adds a cryptographic signature. The browser can carry the cookie but cannot change it without Flask noticing. Understanding exactly what that does and does not protect is the key to using sessions well.

Using the session object

session is imported from flask and behaves like a dict for the current visitor. It needs a SECRET_KEY, the secret used to sign the cookie (see Flash messages for the same requirement).

Python A shopping cart in the 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.

Two clients play two different browsers, and each only sees its own data. session.clear() empties the dictionary and tells the browser to drop the cookie. Prefer session.get("key") over session["key"] for values that might not exist yet.

Mutable values need a nudge

Flask saves the session when it notices a change, and it notices assignments (session["cart"] = ...). If you change a list or dict that already lives inside the session, such as session["cart"].append("pen"), Flask has no way to know, and the change is silently lost. Either assign the value back, as in the example above, or set session.modified = True.

Python The lost append

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 session cookie has three parts separated by dots: the data, a timestamp, and a signature. A diagram of the cookie and the check Flask performs:

flowchart LR
    A["session cookie<br/>payload . timestamp . signature"] --> B["Flask recomputes the<br/>signature with SECRET_KEY"]
    B --> C{"Same as the<br/>one in the cookie?"}
    C -- yes --> D["Accept: session = payload"]
    C -- no --> E["Reject: session = empty"]

The signature proves the payload was written by someone who knows SECRET_KEY.

The payload is only encoded, not encrypted. Anyone can read it. The next example decodes it by hand, then tampers with it twice: once by damaging the signature, once by forging a new payload while keeping the old signature.

Python Readable but tamper-proof

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 consequences are important:

  • Integrity: users cannot change what is in the session (without your key).
  • No secrecy: users can read it. Never put a password, an API key or other private data in it.
  • No revocation: because the data lives in the browser, you cannot reach out and delete one user's session. If a cookie is stolen, it works until it expires.

Choosing and protecting SECRET_KEY

The signature is only as strong as the key. Rules of thumb:

  • Generate a long random value, for example python -c "import secrets; print(secrets.token_hex(32))", and store it in an environment variable or secret manager, never in Git (see Configuration).
  • Use a different key per environment, so a leak of the development key does not matter in production.
  • Changing the key invalidates every existing session, so everyone is logged out. Flask 3.1 lets you list old keys in SECRET_KEY_FALLBACKS to rotate keys without logging everyone out; new cookies are signed with the current key only.

By default the session cookie is a session cookie in the browser sense: it disappears when the browser closes. Setting session.permanent = True gives it an expiry date, taken from PERMANENT_SESSION_LIFETIME (31 days by default). This is how "remember me" is implemented.

Python Permanent sessions

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.

Other session cookie settings live in the config. The most useful ones are SESSION_COOKIE_SECURE = True (HTTPS only), SESSION_COOKIE_SAMESITE = "Lax", SESSION_COOKIE_NAME and SESSION_COOKIE_HTTPONLY, which already defaults to True.

What not to store

Because the session is a small, readable cookie, keep it lean:

  • Do store identifiers and small flags: a user id, a language code, a cart of product ids, a CSRF token.
  • Do not store secrets, personal data you would not print on a postcard, large objects, query results, or anything over a few hundred bytes. Browsers allow about 4 KB per cookie, and the cookie travels with every request.
  • Do not store things that must be revocable instantly, such as "this device is trusted forever". Keep those in your database and keep only a reference in the session.

When you outgrow this model (big carts, immediate logout of a device, sensitive data), the usual step is server-side sessions: the cookie holds only a random session id and the data lives in Redis or a database, for example via the Flask-Session extension. Your view code that uses session[...] stays the same.

For tests, client.session_transaction() lets you read or write the session directly without going through your own login view:

Python
with client.session_transaction() as sess:
    sess["user"] = "ada"

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the signature on Flask's session cookie guarantee?

    The data is signed, not encrypted. The user can read it but cannot alter it without the key.
  2. 2. session["cart"].append("pen") seems to have no effect on the next request. Why?

    Flask detects assignments to session keys, not mutations of objects inside the session.
  3. 3. Which of these is the best thing to keep in a session?

    Sessions should hold small identifiers. Their contents are readable by the user and travel with every request.
  4. 4. What does session.permanent = True change?

    A permanent session survives browser restarts until its lifetime ends. Storage and security are unchanged.
  5. 5. You change SECRET_KEY in production. What happens to existing visitors?

    Old signatures no longer match. SECRET_KEY_FALLBACKS can accept previous keys while you rotate.

Summary

  • session is a per-visitor dictionary stored in a signed cookie; it requires SECRET_KEY.
  • The data is readable by the user but cannot be changed without the key, and you cannot revoke a stolen cookie early.
  • Assign values back (or set session.modified = True) after mutating lists or dicts in place.
  • Use session.clear() to log out, session.permanent = True plus PERMANENT_SESSION_LIFETIME for longer-lived sessions.
  • Keep the key secret and random, per environment; rotate with SECRET_KEY_FALLBACKS.
  • Store small ids and flags, never secrets or large data; move to server-side sessions when you outgrow cookies.

Next: Using sqlite3 with Flask, where your app starts keeping data in a real database.