Web & Internet
Cookies & Sessions
O(1) session lookup — finding a session by its ID takes one step, a single hash-map lookup, no matter how many users are logged in.
The idea, in plain English
A cookie is like the wristband a club gives you at check-in. It's small, it's yours, and the doorman glances at it each time you walk back in, instead of asking for your ID again. HTTP (HyperText Transfer Protocol) is the language browsers and servers use to talk, and it normally forgets you the instant a request finishes. A cookie is a small piece of data the server asks your browser to keep and resend on every future request, so the server can recognize you. A session is the club's actual guest-list entry. It's the real record of who you are, stored on the server and found using the code printed on your wristband.
How it works
- 1On your first visit, you have no wristband yet. The server has no way to tell you apart from a stranger.
- 2When you log in, the server creates a session record — who you are and what you're allowed to do — and stores it under a fresh session ID.
- 3The server tells your browser to remember that session ID as a cookie, and to attach it to every future request to this site.
- 4Your browser automatically resends the cookie on the next request, without you doing anything.
- 5The server reads the cookie, looks up that session ID in its records, and instantly knows who is asking.
When you'd use it
This applies to login systems, shopping carts, 'remember me' features, and anything else that needs to recall who you are across separate requests. Plain HTTP requests are otherwise independent, with no memory between them.
Common beginner mistakes
- Don't think the cookie IS the session. The cookie is just the ticket with an ID printed on it. The actual data — who you are, your permissions — lives in the server's session store, not in the cookie itself.
- Don't forget that if the cookie never comes back — a new browser, it expired, or it was cleared — the server has no memory of you. It treats you as a brand-new stranger.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Visit 1, no cookie: guest (no cookie sent)
Logged in, cookie issued: sess-1
Visit 2, cookie sent: ada
Visit 3, wrong cookie: guest (unknown session)Not sure this is the right topic? See the learning paths → or where this leads →