Skip to content

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.

How cookies are exchanged: 1. the browser requests a page, 2. the server sends the page and a cookie, 3. the browser sends the cookie along when requesting another page from the same server

Image source: Wikimedia Commons (CC BY-SA 3.0)

How Are Cookies Exchanged? ​

Cookies are exchanged through two HTTP headers.

HeaderDirectionWhat it does
Set-CookieServer → browser (response)Tells the browser "please store this value"
CookieBrowser → 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.

Session cookie login flow: a login request, the server returns a session ID cookie, the next request carries the session ID cookie, and the response depends on whether the session is valid

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.

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=Lax

Lifetime: Expires and Max-Age ​

AttributeMeaningExample
ExpiresExpires at a set date and timeExpires=Wed, 21 Oct 2026 07:28:00 GMT
Max-AgeExpires a number of seconds from nowMax-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-Age wins.
  • To delete a cookie, send Max-Age=0 or an Expires date in the past.

Scope: Domain and Path ​

AttributeMeaning
DomainWhich 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
PathWhich 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 ​

AttributeMeaningRisk it prevents
SecureSent only over HTTPS connectionsThe cookie being snooped on over unencrypted traffic
HttpOnlyCannot be read via JavaScript's document.cookieA script injected through XSS stealing the session cookie
SameSiteDecides whether to attach the cookie to requests that start from another siteCSRF, where another site sends requests using my login cookie

SameSite has three values.

ValueIs the cookie attached to requests coming from another site?
StrictNever. Even if you arrive by clicking a link on another site, it may look as if you are logged out at first
LaxAttached for normal navigation (GET) like clicking a link, but not for form POSTs or image/iframe requests sent from another site
NoneAlways 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? ​

  1. When the user logs in, the server creates a session ID as a random string that is hard to guess.
  2. The server records session ID → user info in the session store.
  3. Only the session ID is sent to the browser with Set-Cookie.
  4. On every later request, the browser sends the session ID, and the server looks up the user info in the store.
  5. 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 locationProsCons
Server memoryFastest and simplestRestarting the server logs everyone out. With multiple servers, other servers don't know the session
DatabaseShared by multiple servers, survives restartsEvery request queries the DB, which can slow things down
An in-memory store like RedisFast and shareable by multiple servers, auto-expiry with TTLYou 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.

AspectStoring info directly in a cookieSession (only the session ID in the cookie)
Where the info isBrowserServer (memory, DB, Redis, etc.)
Storage formatString (name=value)Flexible, e.g. objects in the server's language
ExpirySet by Expires / Max-Age; if absent, when the browser closesServer policy (idle timeout, absolute timeout, logout)
Size limitAbout 4KB per cookieNo browser-side limit, but it costs as much as the server storage it takes
Server resourcesBarely usedTakes storage space per user
SecurityUsers can see and edit the value. Never put sensitive info in itThe 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 logoutThe server cannot directly delete a value that lives in the browserDeleting the session on the server invalidates it immediately
UsesTheme, 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.

AspectCookielocalStoragesessionStorage
CapacityAbout 4KB per cookieUsually around 5MB per site (origin)Usually around 5MB per site (origin)
Sent to the server automaticallyYes (every request)NoNo
How long it lastsUntil Expires/Max-Age; if absent, until the browser closesPermanent until you delete itDeleted when the tab closes
Sharing scopeRequests matching Domain/PathAll tabs of the same originOnly within the same tab
Reading with JSdocument.cookie (not possible with HttpOnly)localStorage.getItem()sessionStorage.getItem()
Good usesValues the server needs to know (session ID, etc.)Screen settings like theme or recent searchesTemporarily saving a form being filled in within one tab
  • localStorage and sessionStorage can 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.

python
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's sessions.
  • 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 ​

ConceptOne-line summary
StatelessAn HTTP server does not remember previous requests, which is why cookies and sessions are needed
CookieA small value stored in the browser and sent automatically with every request (the wristband)
SessionThe info is in the server's ledger, the browser holds only the session ID (look up the ledger by wristband number)
Set-Cookie / CookieResponse header where the server orders storage / request header the browser sends back
Expires / Max-AgeCookie lifetime. If absent, deleted when the browser closes
Domain / PathThe scope the cookie is sent to
Secure / HttpOnly / SameSiteHTTPS only / blocks script access / blocks requests from other sites
localStorage / sessionStorageBrowser storage not sent to the server automatically. Permanent / per tab