Cookies

suggest change

HTTP is stateless: each request stands on its own. Cookies are how a server gets a client to remember small pieces of data and send them back. The server sets a cookie with a Set-Cookie response header. The client stores it and returns it in the Cookie header of later requests to the same site:

HTTP/1.1 200 OK
Set-Cookie: sid=a1b2c3; Path=/; HttpOnly; Secure; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=2592000

GET /profile HTTP/1.1
Host: example.com
Cookie: sid=a1b2c3; theme=dark

The server sees only name=value pairs in Cookie. All the attributes are instructions for the client:

Attribute Meaning
Expires=<date> Delete the cookie after this date
Max-Age=<seconds> Delete it after this many seconds. Wins over Expires. 0 deletes it now
(neither) A session cookie, dropped when the browser closes
Domain=example.com Also send to subdomains. Without it, only the exact host that set it gets it
Path=/app Only send for URLs under this path
Secure Only send over HTTPS
HttpOnly JavaScript can't read it through document.cookie
SameSite=Strict|Lax|None Whether to send it on cross-site requests (CSRF protection). None requires Secure

Python covers both sides of this exchange:

All examples were run with Python 3.13, requests 2.34, httpx 0.28 and Flask 3.1.

http.cookies.SimpleCookie is a dict of Morsel objects. Each morsel holds one cookie's value and attributes:

from http.cookies import SimpleCookie

c = SimpleCookie()
c["session_id"] = "a1b2c3"
c["session_id"]["path"] = "/"
c["session_id"]["httponly"] = True
c["session_id"]["secure"] = True
c["session_id"]["samesite"] = "Lax"
c["session_id"]["max-age"] = 3600

c["theme"] = "dark"
c["theme"]["path"] = "/"
c["theme"]["expires"] = 30 * 24 * 3600   # int = seconds from now

print(c["session_id"].OutputString())
print(c.output())
print(repr(c["theme"].value), c["theme"]["path"])
session_id=a1b2c3; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure
Set-Cookie: session_id=a1b2c3; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure
Set-Cookie: theme=dark; expires=Mon, 16 Nov 2026 19:00:07 GMT; Path=/
'dark' /

OutputString() gives the header value for one cookie, which is what you pass to send_header("Set-Cookie", ...). output() returns complete header lines, one per cookie, separated by \r\n. When expires is an integer, SimpleCookie turns it into a date that many seconds from now. You can also pass a ready-made date string, for example from email.utils.format_datetime(dt, usegmt=True).

Each cookie must be sent as a separate Set-Cookie header. Never join them with commas: dates in Expires contain commas, so clients can't split the result.

On the server you get the raw Cookie header. load(), or passing the string to the constructor, parses it:

from http.cookies import SimpleCookie, CookieError

# parse a Cookie request header
c = SimpleCookie()
c.load("session_id=a1b2c3; theme=dark; lang=en-US")
for name, morsel in c.items():
    print(name, "=", morsel.value)
print({k: m.value for k, m in c.items()})

# values with special characters are quoted
c = SimpleCookie()
c["msg"] = "hello world; bye"
print(c.output(header="Cookie:"))

c2 = SimpleCookie()
c2.load(c["msg"].OutputString())
print(repr(c2["msg"].value))

try:
    c["bad name"] = "x"
except CookieError as e:
    print("CookieError:", e)

# a single bad pair makes load() skip everything after it
c3 = SimpleCookie()
c3.load('a=1; b="unterminated; c=3')
print(dict((k, m.value) for k, m in c3.items()))
session_id = a1b2c3
theme = dark
lang = en-US
{'session_id': 'a1b2c3', 'theme': 'dark', 'lang': 'en-US'}
Cookie: msg="hello world\073 bye"
'hello world; bye'
CookieError: Illegal key 'bad name'
{'a': '1'}

Two things to note here:

To store arbitrary text, encode it yourself so that the value contains only safe characters. Percent-encoding works well:

from http.cookies import SimpleCookie
from urllib.parse import quote, unquote

c = SimpleCookie()
c["name"] = quote("Zoë Kowalska, Kraków")
print(c.output())

back = SimpleCookie("name=" + c["name"].value)
print(unquote(back["name"].value))
Set-Cookie: name=Zo%C3%AB%20Kowalska%2C%20Krak%C3%B3w
Zoë Kowalska, Kraków

For structured data, use JSON plus URL-safe base64, or better, a signed value (see "Signed cookies" below).

A small server that uses cookies

The client examples below talk to this local server, built on http.server. /login creates a session and sets two cookies, /me reports which user and which cookies it received, and /logout deletes the session cookie by setting Max-Age=0:

# cookie_server.py
import secrets
import threading
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

SESSIONS = {}  # session id -> user name

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        cookies = SimpleCookie(self.headers.get("Cookie", ""))
        out = SimpleCookie()

        if self.path.startswith("/login"):
            sid = secrets.token_urlsafe(16)
            SESSIONS[sid] = "alice"
            out["sid"] = sid
            out["sid"].update({"path": "/", "httponly": True, "samesite": "Lax"})
            out["theme"] = "dark"
            out["theme"].update({"path": "/", "max-age": 86400})
            body = "logged in"
        elif self.path == "/me":
            sid = cookies["sid"].value if "sid" in cookies else None
            body = f"user={SESSIONS.get(sid)} cookies={sorted(cookies)}"
        elif self.path == "/logout":
            if "sid" in cookies:
                SESSIONS.pop(cookies["sid"].value, None)
            out["sid"] = ""
            out["sid"].update({"path": "/", "max-age": 0})
            body = "logged out"
        else:
            self.send_error(404)
            return

        data = body.encode()
        self.send_response(200)
        for morsel in out.values():
            self.send_header("Set-Cookie", morsel.OutputString())
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, format, *args):
        pass

def start(port=8000):
    server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server

The session ID comes from secrets.token_urlsafe(), so it can't be guessed. The cookie holds only that random ID, and the real data ("alice") stays on the server. To delete a cookie, send it again with the same name, Path and Domain plus Max-Age=0. If the path or domain don't match, the client treats it as a different cookie and keeps the old one. See Basic handling of GET POST PUT using BaseHTTPRequestHandler for more about http.server.

Client side: urllib and http.cookiejar

urllib.request ignores cookies by default. To get browser-like behavior, give an opener an HTTPCookieProcessor with a CookieJar. The jar saves cookies from responses and adds the matching ones to each request:

import urllib.request
from http.cookiejar import CookieJar
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"

jar = CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))

for path in ["/me", "/login", "/me"]:
    with opener.open(BASE + path) as resp:
        print(path, "->", resp.read().decode())

for c in jar:
    print(f"{c.name}={c.value[:6]}... domain={c.domain} path={c.path} "
          f"expires={c.expires} httponly={c.has_nonstandard_attr('HttpOnly')}")

with opener.open(BASE + "/logout") as resp:
    print("/logout ->", resp.read().decode())
print([c.name for c in jar])
with opener.open(BASE + "/me") as resp:
    print("/me ->", resp.read().decode())
/me -> user=None cookies=[]
/login -> logged in
/me -> user=alice cookies=['sid', 'theme']
sid=NdocK0... domain=127.0.0.1 path=/ expires=None httponly=True
theme=dark... domain=127.0.0.1 path=/ expires=1792350022 httponly=False
/logout -> logged out
['theme']
/me -> user=None cookies=['theme']

Each item in the jar is an http.cookiejar.Cookie. expires is a Unix timestamp, or None for a session cookie. HttpOnly and SameSite aren't standard attributes in the old cookie RFC, so you check them with has_nonstandard_attr(). When the server sent Max-Age=0 for sid, the jar removed the cookie.

Saving cookies to a file

MozillaCookieJar reads and writes the Netscape cookies.txt format, which curl and wget also use:

import urllib.request
from http.cookiejar import MozillaCookieJar
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"

jar = MozillaCookieJar("cookies.txt")
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
opener.open(BASE + "/login").close()

jar.save()                          # session cookie "sid" is skipped
print(open("cookies.txt").read().splitlines()[-1])
jar.save(ignore_discard=True)       # keep session cookies too
print(len(open("cookies.txt").read().splitlines()))

# a fresh jar loaded from the file
jar2 = MozillaCookieJar()
jar2.load("cookies.txt", ignore_discard=True)
print(sorted(c.name for c in jar2))
opener2 = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar2))
with opener2.open(BASE + "/me") as resp:
    print(resp.read().decode())
127.0.0.1	FALSE	/	FALSE	1792350031	theme	dark
6
['sid', 'theme']
user=alice cookies=['sid', 'theme']

The file is plain text with one tab-separated line per cookie: domain, include-subdomains flag, path, secure flag, expiry timestamp, name and value:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file!  Do not edit.

127.0.0.1	FALSE	/	FALSE		sid	b5B2h7-gV_WeFnSl9QJVRQ
127.0.0.1	FALSE	/	FALSE	1792350031	theme	dark

By default save() and load() skip session cookies (ignore_discard=False) and expired cookies (ignore_expires=False). Pass ignore_discard=True when you want a login session to survive a restart of your script. The file then contains a live session token, so protect it like a password.

Cookies with requests

requests (pip install requests) puts the cookies a response set into response.cookies. Module-level functions like requests.get() start with an empty jar on every call, so they don't send anything back. A Session keeps a jar in session.cookies and sends its cookies on every request:

import requests
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"

# plain requests.get() does not remember cookies between calls
r = requests.get(BASE + "/login")
print(r.cookies.get_dict().keys())
print(requests.get(BASE + "/me").text)

# send cookies explicitly with cookies=
print(requests.get(BASE + "/me", cookies={"theme": "light", "lang": "pl"}).text)

# a Session stores them in session.cookies and sends them back
with requests.Session() as s:
    s.get(BASE + "/login")
    print(s.get(BASE + "/me").text)
    print(s.cookies.get("theme"), len(s.cookies))
    for c in s.cookies:
        print(c.name, c.domain, c.path, c.expires)
    s.get(BASE + "/logout")
    print(s.cookies.keys())
dict_keys(['sid', 'theme'])
user=None cookies=[]
user=None cookies=['lang', 'theme']
user=alice cookies=['sid', 'theme']
dark 2
sid 127.0.0.1 / None
theme 127.0.0.1 / 1792350038
['theme']

session.cookies is a RequestsCookieJar, a CookieJar subclass with a dict-like interface on top. See Sessions for the other things a session keeps, such as headers, auth and connection pooling.

Setting cookies with a domain and path

cookies.set() takes the same scoping rules a server would send. A cookie is only sent to hosts and paths that match:

import requests
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"

s = requests.Session()
s.cookies.set("lang", "pl")                               # any host
s.cookies.set("token", "t-123", domain="api.example.com") # only that host
s.cookies.set("admin", "1", domain="127.0.0.1", path="/admin")

r = s.get(BASE + "/me")
print(r.text)
print(r.request.headers.get("Cookie"))

# per-request cookies are merged in, but not saved in the session
r = s.get(BASE + "/me", cookies={"debug": "1"})
print(r.request.headers["Cookie"])
print(sorted(s.cookies.keys()))

# the same name can exist for several domains
s.cookies.set("lang", "en", domain="api.example.com")
try:
    s.cookies["lang"]
except requests.cookies.CookieConflictError as e:
    print("CookieConflictError:", e)
print(s.cookies.get("lang", domain="api.example.com"))
user=None cookies=['lang']
lang=pl
lang=pl; debug=1
['admin', 'lang', 'token']
CookieConflictError: There are multiple cookies with name, 'lang'
en

r.request.headers["Cookie"] shows exactly what was sent, which helps a lot when debugging. token wasn't sent because the host didn't match, and admin wasn't sent because the path didn't. A cookie set without a domain goes to every host, so a token set that way also leaks to any third-party URL you request with the same session. Always give sensitive cookies a domain.

Persisting a requests session

You can replace session.cookies with any http.cookiejar.CookieJar, including MozillaCookieJar, which gives you saving and loading for free:

import os
from http.cookiejar import MozillaCookieJar
import requests
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"
COOKIE_FILE = "session_cookies.txt"

def make_session():
    s = requests.Session()
    s.cookies = MozillaCookieJar(COOKIE_FILE)
    if os.path.exists(COOKIE_FILE):
        s.cookies.load(ignore_discard=True, ignore_expires=True)
    return s

s = make_session()
s.get(BASE + "/login")
s.cookies.save(ignore_discard=True, ignore_expires=True)
s.close()

s = make_session()           # e.g. the next time the script runs
print(s.get(BASE + "/me").text)
print(type(s.cookies).__name__)
user=alice cookies=['sid', 'theme']
MozillaCookieJar

A common shortcut is to save dict_from_cookiejar(s.cookies) as JSON. It works, but it drops the domain, path and expiry of each cookie:

import requests
from requests.utils import dict_from_cookiejar, cookiejar_from_dict

jar = requests.cookies.RequestsCookieJar()
jar.set("sid", "abc", domain="example.com", path="/app")
d = dict_from_cookiejar(jar)
print(d)
jar2 = cookiejar_from_dict(d)
c = next(iter(jar2))
print(c.name, repr(c.domain), c.path)
{'sid': 'abc'}
sid '' /

After the round trip, the cookie is sent to every host again.

Cookies with httpx

httpx works the same way. A Client keeps an httpx.Cookies object, which wraps a standard CookieJar:

import httpx
import cookie_server

cookie_server.start(8000)
BASE = "http://127.0.0.1:8000"

with httpx.Client(base_url=BASE) as client:
    r = client.get("/login")
    print(dict(r.cookies))
    print(client.get("/me").text)
    client.cookies.set("lang", "pl", domain="127.0.0.1")
    print(client.get("/me").text)
    print(client.cookies.jar.__class__.__name__)
{'sid': 'LsI-RJI3UmleK1-0yne-xw', 'theme': 'dark'}
user=alice cookies=['sid', 'theme']
user=alice cookies=['lang', 'sid', 'theme']
CookieJar

Set cookies on the client, not on each request. Newer httpx versions deprecate the per-request cookies= argument, because those cookies would bypass the client's jar.

Cookies in Flask

In Flask, request.cookies is a dict of the incoming cookies, and response.set_cookie() / response.delete_cookie() add Set-Cookie headers:

# app.py
from datetime import timedelta
from flask import Flask, request, make_response

app = Flask(__name__)

@app.get("/")
def index():
    theme = request.cookies.get("theme", "light")
    visits = int(request.cookies.get("visits", "0")) + 1
    resp = make_response(f"theme={theme} visits={visits}")
    resp.set_cookie("visits", str(visits), max_age=timedelta(days=365),
                    httponly=True, samesite="Lax")
    return resp

@app.post("/theme/<name>")
def set_theme(name):
    resp = make_response("ok")
    resp.set_cookie("theme", name, max_age=30 * 24 * 3600, samesite="Lax")
    return resp

@app.post("/reset")
def reset():
    resp = make_response("reset")
    resp.delete_cookie("visits")
    resp.delete_cookie("theme")
    return resp

Flask's test client stores cookies between requests just like a browser does, so you can try the app without starting a server:

from app import app

client = app.test_client()
print(client.get("/").text)
r = client.get("/")
print(r.text)
print(r.headers.getlist("Set-Cookie"))

client.post("/theme/dark")
print(client.get("/").text)
print(client.get_cookie("theme").value)

r = client.post("/reset")
for h in r.headers.getlist("Set-Cookie"):
    print(h)
print(client.get("/").text)
theme=light visits=1
theme=light visits=2
['visits=2; Expires=Sun, 17 Oct 2027 19:01:14 GMT; Max-Age=31536000; HttpOnly; Path=/; SameSite=Lax']
theme=dark visits=3
dark
visits=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
theme=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
theme=light visits=1

set_cookie() writes both Max-Age and Expires, for old clients that only understand Expires. delete_cookie() sets an empty value with an expiry in the past. If you set the cookie with a path or domain, pass the same values to delete_cookie().

A visits counter in a plain cookie is fine for a demo, but the user can edit it. Never trust a plain cookie value for anything that matters, such as a user ID, a role or a price. Flask's built-in session is a signed cookie. See Sessions.

Signed cookies

When you have to keep data on the client, sign it so that the server can detect tampering. itsdangerous is installed with Flask, and Flask's session uses it internally:

from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired

signer = URLSafeTimedSerializer("change-me-to-a-long-random-secret", salt="cart")

value = signer.dumps({"user_id": 42, "items": [7, 9]})
print(value)

print(signer.loads(value, max_age=3600))

# signed is not encrypted: anyone can read the payload
import base64
print(base64.urlsafe_b64decode(value.split(".")[0] + "=="))

tampered = value.replace("eyJ1c2VyX2lkIjo0Mi", "eyJ1c2VyX2lkIjo0My")
try:
    signer.loads(tampered)
except BadSignature as e:
    print("rejected:", type(e).__name__)

import time
time.sleep(2)
try:
    signer.loads(value, max_age=1)
except SignatureExpired as e:
    print("rejected:", type(e).__name__)
eyJ1c2VyX2lkIjo0MiwiaXRlbXMiOls3LDldfQ.atPGDA.liEuubt1c92PEj8jCvuogj1D7KI
{'user_id': 42, 'items': [7, 9]}
b'{"user_id":42,"items":[7,9]}'
rejected: BadTimeSignature
rejected: SignatureExpired

The value has three parts: the base64 payload, a timestamp and an HMAC signature. Changing user_id from 42 to 43 invalidates the signature. max_age lets you reject old values even if the browser still has the cookie. Signing doesn't hide anything, though: the payload is just base64. Don't put secrets in it, and keep the signing key out of source control.

Security checklist

Summary

Task Code
Build a Set-Cookie value c = SimpleCookie(); c["k"] = "v"; c["k"]["httponly"] = True; c["k"].OutputString()
Parse a Cookie header SimpleCookie(header), then {k: m.value for k, m in c.items()}
Delete a cookie same name, path and domain with Max-Age=0
urllib with cookies build_opener(HTTPCookieProcessor(CookieJar()))
Save / load cookies MozillaCookieJar(path).save(ignore_discard=True) / .load(...)
requests: read r.cookies.get("k"), session.cookies.get_dict()
requests: send requests.get(url, cookies={"k": "v"}) or session.cookies.set("k", "v", domain=...)
requests: persist session.cookies = MozillaCookieJar(path)
See what was sent r.request.headers.get("Cookie")
httpx client.cookies.set(...), r.cookies
Flask: read request.cookies.get("k")
Flask: write / delete resp.set_cookie("k", "v", max_age=..., httponly=True, samesite="Lax") / resp.delete_cookie("k")
Sign a value URLSafeTimedSerializer(secret).dumps(obj) / .loads(s, max_age=...)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents