Cookie & Session
A cookie is a small piece of data stored in the browser and automatically sent to the server with every request. A session stores user information on the server side and gives the browser only a key (the session ID) to look that information up. Both are used so that "the server can remember who just sent the request."
At a Glance
- HTTP is fundamentally a stateless protocol. The server receives each request as a new, unrelated request. So even if you logged in once, the server cannot tell on the next request that you are "the same person as before" unless you tell it separately.
- Analogy: think of an amusement park.
- A cookie is the wristband put on your wrist. You wear the wristband, and it is automatically shown to the staff (the server) every time you get on a ride.
- A session is when the staff look up the information desk's ledger using the number written on the wristband. The wristband only has a number; the real information, like "all-day pass, height 140cm or more," is written in the information desk's ledger (the server).
- That is why sessions, too, almost always send the session ID back and forth in a cookie. It is easier to understand cookies and sessions not as competing technologies but as a difference in "where the information is kept."
As in the image below, when the server sends a cookie along with a page, the browser presents that cookie every time it makes another request to the same server.

Image source: Wikimedia Commons (CC BY-SA 3.0)
How Are Cookies Exchanged?
Cookies are exchanged through two HTTP headers.
| Header | Direction | What it does |
|---|---|---|
Set-Cookie | Server → browser (response) | Tells the browser "please store this value" |
Cookie | Browser → server (request) | Automatically carries the stored cookies whose conditions match |
Drawing the login process as a text diagram looks like this.
[1] Browser → Server POST /login (ID, password)
Server: after checking the password, records {abc123: 1mo} in the session store
[2] Server → Browser 200 OK
Set-Cookie: session_id=abc123
Browser: stores the cookie
[3] Browser → Server GET /mypage
Cookie: session_id=abc123
Server: looks up abc123 in the ledger → 1mo
[4] Server → Browser 200 OK (1mo's My Page)The same flow as a picture looks like this.

Image source: MDN, Using HTTP cookies (CC BY-SA 2.5)
Without the developer writing any extra code, the browser automatically attaches cookies to every request when the conditions (domain, path, expiry, etc.) match. This "attached automatically" property is what makes cookies convenient, and at the same time it is what makes a CSRF attack possible.
Cookie Attributes
Besides the value, you can attach several attributes to the Set-Cookie header to set the cookie's lifetime, scope, and security level.
Set-Cookie: session_id=abc123; Max-Age=1800; Path=/; Secure; HttpOnly; SameSite=LaxLifetime: Expires and Max-Age
| Attribute | Meaning | Example |
|---|---|---|
Expires | Expires at a set date and time | Expires=Wed, 21 Oct 2026 07:28:00 GMT |
Max-Age | Expires a number of seconds from now | Max-Age=1800 (30 minutes) |
- If neither is set, it becomes a session cookie that disappears when you close the browser. (However, because of "restore previous tabs" features, modern browsers sometimes keep it even after closing and reopening.)
- If both are set,
Max-Agewins. - To delete a cookie, send
Max-Age=0or anExpiresdate in the past.
Scope: Domain and Path
| Attribute | Meaning |
|---|---|
Domain | Which domain to send it to. If omitted, it is sent only to the exact host that created the cookie. With Domain=example.com, it is also sent to subdomains like api.example.com |
Path | Which path's requests to send it with. With Path=/admin, it is attached only to /admin and /admin/users requests |
A wider scope is more convenient, but the cookie spreads to places that don't need it, so it is best to set only as much as you need.
Security: Secure, HttpOnly, SameSite
| Attribute | Meaning | Risk it prevents |
|---|---|---|
Secure | Sent only over HTTPS connections | The cookie being snooped on over unencrypted traffic |
HttpOnly | Cannot be read via JavaScript's document.cookie | A script injected through XSS stealing the session cookie |
SameSite | Decides whether to attach the cookie to requests that start from another site | CSRF, where another site sends requests using my login cookie |
SameSite has three values.
| Value | Is the cookie attached to requests coming from another site? |
|---|---|
Strict | Never. Even if you arrive by clicking a link on another site, it may look as if you are logged out at first |
Lax | Attached for normal navigation (GET) like clicking a link, but not for form POSTs or image/iframe requests sent from another site |
None | Always attached. But it must be used together with Secure |
Chrome and several other browsers treat a cookie without SameSite as Lax. Still, the default behavior differs a little between browsers, so it is safer to set it explicitly.
Size Limits
Because cookies ride along automatically with every request, they must be kept small. The standard (RFC 6265) says browsers must be able to store at least 4KB per cookie and at least 50 cookies per domain, and real browsers often allow a bit more. As cookies grow, every request becomes that much heavier.
How Do Sessions Work?
- When the user logs in, the server creates a session ID as a random string that is hard to guess.
- The server records
session ID → user infoin the session store. - Only the session ID is sent to the browser with
Set-Cookie. - On every later request, the browser sends the session ID, and the server looks up the user info in the store.
- On logout, or when there are no requests for a certain time, the server removes the session from the store.
Where Should the Session Store Live?
| Storage location | Pros | Cons |
|---|---|---|
| Server memory | Fastest and simplest | Restarting the server logs everyone out. With multiple servers, other servers don't know the session |
| Database | Shared by multiple servers, survives restarts | Every request queries the DB, which can slow things down |
| An in-memory store like Redis | Fast and shareable by multiple servers, auto-expiry with TTL | You have to run a separate server |
When you scale to multiple servers, you get the problem of "I logged in on server 1, but my request went to server 2 and I got logged out." That is why, in practice, a session store that all servers share, like Redis, is common.
When Does a Session Expire?
Rather than being "unknown," a session's expiry is set by the server as a policy. Usually two kinds are used together.
- Idle timeout: expires if there are no requests for 30 minutes after the last one
- Absolute timeout: expires 12 hours after login, no matter how actively you use it
From the browser's (client's) point of view, it cannot directly see when the server deleted the session, so it only finds out when it sends the next request and gets a "login required" response.
Cookie vs Session
| Aspect | Storing info directly in a cookie | Session (only the session ID in the cookie) |
|---|---|---|
| Where the info is | Browser | Server (memory, DB, Redis, etc.) |
| Storage format | String (name=value) | Flexible, e.g. objects in the server's language |
| Expiry | Set by Expires / Max-Age; if absent, when the browser closes | Server policy (idle timeout, absolute timeout, logout) |
| Size limit | About 4KB per cookie | No browser-side limit, but it costs as much as the server storage it takes |
| Server resources | Barely used | Takes storage space per user |
| Security | Users can see and edit the value. Never put sensitive info in it | The real info is on the server, so it is relatively safe. But if the session ID is stolen, the thief can impersonate the user |
| Forced logout | The server cannot directly delete a value that lives in the browser | Deleting the session on the server invalidates it immediately |
| Uses | Theme, language settings, "Don't show again today" | Login state, shopping cart, permission info |
Browser Storage Compared at a Glance
Cookies are not the only way to keep data in the browser. This site's dark mode feature also stores the theme in localStorage, not in a cookie. The server doesn't need to know the theme value, so localStorage is a better fit than a cookie that rides along with every request.
| Aspect | Cookie | localStorage | sessionStorage |
|---|---|---|---|
| Capacity | About 4KB per cookie | Usually around 5MB per site (origin) | Usually around 5MB per site (origin) |
| Sent to the server automatically | Yes (every request) | No | No |
| How long it lasts | Until Expires/Max-Age; if absent, until the browser closes | Permanent until you delete it | Deleted when the tab closes |
| Sharing scope | Requests matching Domain/Path | All tabs of the same origin | Only within the same tab |
| Reading with JS | document.cookie (not possible with HttpOnly) | localStorage.getItem() | sessionStorage.getItem() |
| Good uses | Values the server needs to know (session ID, etc.) | Screen settings like theme or recent searches | Temporarily saving a form being filled in within one tab |
localStorageandsessionStoragecan be read by JavaScript at any time, so an XSS attack exposes their contents completely. That is why people say it is risky to keep login tokens there. This is covered in detail in the storage location part of the JWT article.- For large or offline data, browsers use a built-in database called
IndexedDB.
Getting a Feel with Code: Imitating a Session Login
Let's create a Set-Cookie header with the Python standard library http.cookies and imitate the login flow by using a dictionary as the session store.
from http.cookies import SimpleCookie
import secrets
# session store in server memory (session ID -> user info)
sessions = {}
def login(username):
session_id = secrets.token_hex(8) # a random string that is hard to guess
sessions[session_id] = {"user": username} # the real info is stored only on the server
cookie = SimpleCookie()
cookie["session_id"] = session_id
cookie["session_id"]["path"] = "/"
cookie["session_id"]["httponly"] = True
cookie["session_id"]["secure"] = True
cookie["session_id"]["samesite"] = "Lax"
cookie["session_id"]["max-age"] = 1800
return cookie.output() # one response header line
def handle_request(cookie_header):
cookie = SimpleCookie()
cookie.load(cookie_header) # read the Cookie header the browser sent
sid = cookie["session_id"].value if "session_id" in cookie else None
info = sessions.get(sid)
return f"Hello, {info['user']}" if info else "Login required"
# 1) Login response: the server sends a Set-Cookie header
set_cookie = login("1mo")
print(set_cookie)
# 2) Next request: the browser carries only the session ID in the Cookie header
sid = list(sessions)[0]
print(handle_request(f"session_id={sid}"))
# 3) A request with no cookie, or with a bogus session ID
print(handle_request(""))
print(handle_request("session_id=0000000000000000"))
# 4) Logout: once the server deletes the session, sending the same cookie is useless
del sessions[sid]
print(handle_request(f"session_id={sid}"))Output (the session ID changes every time you run it):
Set-Cookie: session_id=f9fa39f1081e11e6; HttpOnly; Max-Age=1800; Path=/; SameSite=Lax; Secure
Hello, 1mo
Login required
Login required
Login required- All that went to the browser is the meaningless string
f9fa39f1081e11e6; the information "1mo" exists only in the server'ssessions. - As in the last line, once the server deletes the session, you are logged out even if the browser keeps sending the same cookie. This is why forced logout is easy with sessions.
Interview Questions
Q. What is the difference between a cookie and a session? A. A cookie stores data in the browser and sends it automatically with every request, while a session stores data on the server and gives the browser only the session ID as a cookie. Sessions are safer but use server resources, and with multiple servers the session store must be shared.
Q. HTTP is stateless, so how is a login kept? A. After login, the server sends a session ID or token with Set-Cookie, and the browser sends it back in the Cookie header on every later request, so the server can tell it is the same user.
Q. Which attributes should you use to make a session cookie secure? A. Use Secure to send it only over HTTPS, HttpOnly so scripts cannot read it, and SameSite=Lax or Strict so it is not attached to requests from other sites, all together.
Q. What problems happen with sessions when you scale to multiple servers? A. If the server you logged in on differs from the server that receives the next request, the session cannot be found. You can use sticky sessions that send the same user to the same server, set up a shared session store like Redis, or consider a token approach (JWT) that keeps no state on the server.
Q. Why issue a new session ID after a successful login? A. To prevent a session fixation attack, where an attacker plants a session ID they already know on the victim, and when the victim logs in with that ID, the attacker can use the same ID to be logged in too.
Summary
| Concept | One-line summary |
|---|---|
| Stateless | An HTTP server does not remember previous requests, which is why cookies and sessions are needed |
| Cookie | A small value stored in the browser and sent automatically with every request (the wristband) |
| Session | The info is in the server's ledger, the browser holds only the session ID (look up the ledger by wristband number) |
Set-Cookie / Cookie | Response header where the server orders storage / request header the browser sends back |
Expires / Max-Age | Cookie lifetime. If absent, deleted when the browser closes |
Domain / Path | The scope the cookie is sent to |
Secure / HttpOnly / SameSite | HTTPS only / blocks script access / blocks requests from other sites |
| localStorage / sessionStorage | Browser storage not sent to the server automatically. Permanent / per tab |
