Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 72 ยท State: Sessions and Cookies

Cookies

Learn to set, read and delete cookies in Flask, what HttpOnly, Secure, SameSite, Max-Age and Path do, and how the test client's cookie jar works.

HTTP has no memory. Every request arrives as a stranger, and the server answers without knowing what happened a second ago. Cookies are the browser's fix: the server sends a small name=value pair in a Set-Cookie header, the browser stores it, and from then on the browser attaches it to matching requests in a Cookie header.

In this lesson you will set, read and delete cookies with Flask, learn what each cookie attribute protects against, and use the test client's cookie jar, which behaves like a tiny browser. Flask's own session is built on top of a cookie, so this is the foundation for the next lesson.

Here is the whole conversation for a "dark theme" preference:

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: GET /theme/dark
    F-->>B: 200 + Set-Cookie: theme=dark
    Note over B: stores the cookie
    B->>F: GET /show (Cookie: theme=dark)
    F-->>B: 200 "theme is dark"

The server writes with Set-Cookie; the browser replays the value with Cookie on later requests.

Setting and reading cookies

You cannot set a cookie on a plain string; it belongs to a response object. Use make_response() (see Responses) to get one, call set_cookie(), and return it. Incoming cookies are in request.cookies, a read-only dictionary of strings.

Python Set, read and delete a cookie

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.

Always read cookies with .get(name, default). A new visitor, or someone who cleared their cookies, will not have the key, and request.cookies["theme"] would then answer with a 400 Bad Request.

Cookie values are always strings. Convert numbers yourself, and be defensive about it, because the browser (or an attacker) can send anything:

Python
raw = request.cookies.get("visits", "0")
visits = int(raw) if raw.isdigit() else 0

set_cookie() accepts keyword arguments that become attributes of the Set-Cookie header. These decide how long the cookie lives, who may read it and when the browser sends it.

Argument Header attribute Meaning
max_age=3600 Max-Age Lifetime in seconds. Without it (and without expires) the cookie is a session cookie that disappears when the browser closes.
expires=... Expires Absolute expiry date. max_age is simpler.
path="/app" Path Only send the cookie for URLs under this path. Default /.
domain=... Domain Share across subdomains. Leave it out to keep the cookie host-only.
httponly=True HttpOnly JavaScript cannot read it through document.cookie.
secure=True Secure The browser only sends it over HTTPS.
samesite="Lax" SameSite Controls sending on cross-site requests: Strict, Lax or None.

What these defend against:

  • HttpOnly limits the damage of a cross-site scripting (XSS) bug, because injected scripts cannot steal the cookie. Use it for anything sensitive.
  • Secure stops the cookie from travelling in clear text on plain HTTP.
  • SameSite reduces cross-site request forgery. Lax (the default in modern browsers) blocks the cookie on cross-site POSTs and sub-requests but allows it when the user follows a normal link. Strict is tighter, None requires Secure and sends it everywhere.

Print the header Flask produces to see the attributes. The Expires date changes with the clock, so this example drops it:

Python Reading the Set-Cookie header

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 first cookie shows every attribute; the second shows what a bare set_cookie("banner_seen", "1") gives you: a session cookie with Path=/ and no protection flags. Add the flags deliberately.

You can set app-wide defaults for the session cookie with SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SECURE and SESSION_COOKIE_SAMESITE. They do not affect cookies you set yourself with set_cookie().

A server cannot reach into the browser and remove a cookie. It asks the browser to do it by sending the same cookie again with an expiry in the past. response.delete_cookie("theme") does exactly that (it sends an empty value and Max-Age=0). If you set the cookie with a custom path or domain, pass the same values to delete_cookie(), or the browser will treat it as a different cookie and keep the original.

app.test_client() keeps a cookie jar like a browser would. Cookies from Set-Cookie headers are stored and sent back automatically, and the jar honors each cookie's path. You can also manipulate it directly:

  • client.get_cookie("name") returns a cookie object (or None) with .value, .path, .max_age, .http_only and more.
  • client.set_cookie("name", "value") plants a cookie, as if the browser already had it.
  • client.delete_cookie("name") removes one.

One difference from a real browser: the test client does not hold back a Secure cookie on plain http:// requests, so you cannot use it to verify that behavior. You can still assert that the attribute is present.

Python A visit counter, and a forged cookie

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 counter climbs across requests because the jar remembers the cookie; a second client starts again at 1. The last part is the key lesson: a plain cookie is user input. Anyone can edit it in their browser's developer tools, so a role=admin cookie proves nothing. Never store passwords, permissions, prices or anything you must trust in a plain cookie.

When to use cookies directly

Plain cookies suit harmless preferences: theme, language, "dismissed this banner", a consent choice. For anything the server must trust, such as who is logged in, use Flask's signed session instead: it uses the same mechanism but adds a signature, so tampering is detected. That is the topic of the next lesson.

Two other practical points:

  • Browsers cap cookies at roughly 4 KB each and limit how many a site may set. Cookies also ride along on every request to the site, including images, so keep them small.
  • In Europe and other regions, non-essential cookies (analytics, advertising) need consent. Preference cookies the user asked for are usually fine, but check the rules that apply to you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you attach a cookie to a Flask response?

    Cookies are set on a response object. request.cookies is read-only and holds what the browser sent.
  2. 2. What does the HttpOnly attribute do?

    HttpOnly keeps document.cookie from exposing the value, which limits what an XSS bug can steal. It does not encrypt anything.
  3. 3. A cookie was set with path="/app". What must you do to delete it?

    A cookie is identified by name, domain and path. Deleting with a different path targets a different cookie.
  4. 4. Why is if request.cookies.get("role") == "admin" a bad access check?

    A plain cookie is user input. Use a signed session or a server-side record to remember who someone is.
  5. 5. A visitor has no visits cookie yet. What is the safest way to read it?

    .get() with a default avoids the 400 error from a missing key, and the string still needs careful conversion to an int.

Summary

  • A cookie is a name=value pair the server sets with Set-Cookie and the browser returns in Cookie.
  • Set cookies on a response (make_response + set_cookie); read them from request.cookies with .get(); delete with delete_cookie() using the same path and domain.
  • Without max_age or expires a cookie lasts only until the browser closes.
  • Use HttpOnly, Secure and SameSite deliberately; set_cookie() does not turn them on for you.
  • Cookie values are strings controlled by the client, so never trust them for permissions or prices.
  • The test client's cookie jar stores, sends, and lets you inspect cookies like a small browser.

Next: Sessions, tamper-proof per-user state built on a signed cookie.