1 minute read

Cookies and sessions are both ways to persist data across HTTP requests, but they work differently:

  • Stored on the client (browser)
  • Data is sent with every HTTP request in the request header
  • Can persist for a set expiration time (even after the browser closes)
  • Limited to about 4KB of data
  • Can be read by JavaScript (unless HttpOnly flag is set)
  • Examples: remembering a user’s theme preference, tracking analytics

Session

  • Stored on the server
  • The browser only holds a small session ID (usually in a cookie)
  • Typically expires when the browser is closed (or after a server-defined timeout)
  • Can hold much larger amounts of data
  • More secure since the actual data never leaves the server
  • Examples: storing login state, shopping cart contents

How they work together

Browser                          Server
  |                                |
  |--- Request (with session ID) ->|
  |                                |--- Looks up session ID in store
  |                                |--- Retrieves session data
  |<-- Response -------------------|

A common pattern is: the server creates a session, stores the session ID in a cookie, and on each request the browser sends that cookie so the server can find the right session data.

Quick comparison

Feature Cookie Session
Storage location Client (browser) Server
Size limit ~4KB No strict limit
Lifetime Configurable Usually browser session
Security Less secure More secure
Performance Faster (no server lookup) Slightly slower
Use case Preferences, tracking Auth, sensitive data

Rule of thumb: Use cookies for small, non-sensitive data you’re okay storing client-side. Use sessions for sensitive data or anything that shouldn’t be exposed to the client.

Updated: