Skip to content

How Does a Cookie Actually Work?

I used to think that the web was one continuous conversation. I log in, and the website "remembers" me while I browse.

But the truth is, the web is stateless. Every time you click a link, it's like meeting the server for the first time. It has no idea who you are or what you did five seconds ago.

Cookies are the sticky notes that solve this problem.

The Big Picture: The Sticky Note System

sequenceDiagram
    participant Browser
    participant Server
    Browser->>Server: POST /login (username/password)
    Server-->>Browser: 200 OK (Set-Cookie: session_id=123)
    Note right of Browser: Browser saves the sticky note!
    Browser->>Server: GET /profile (Cookie: session_id=123)
    Server-->>Browser: 200 OK (Hello, Nadeem!)

When you log in, the server creates a unique ID for you. It sends this back in a special header called Set-Cookie. Your browser sees this and says, "Okay, I'll save this for later."

Now, every single time you make a request to that same server, your browser automatically attaches that cookie. It's like wearing a name tag. The server looks at the name tag, checks its database, and says, "Oh, it's Nadeem again! I'll show him his profile."


Wait, but why?

Why not just stay connected? Keeping millions of connections open at once would crash the server. By being stateless and using cookies, the server can "forget" about you until the very moment you ask for something. It's much more efficient.


Common gotchas

  • I always forget that cookies are tied to a specific domain. A cookie set by google.com won't be sent to facebook.com.
  • Watch out for "Third-Party Cookies": These are set by domains other than the one you are visiting (like an ad network). Browsers are starting to block these for privacy reasons.
  • Secure and HttpOnly: These are flags the server can set to make sure your cookies can't be stolen by malicious scripts.

Try it yourself

You can see your own cookies right now: 1. Open your browser's Developer Tools (F12 or Cmd+Opt+I). 2. Go to the Application tab (or Storage in Firefox). 3. Click on Cookies in the sidebar.

You'll see a list of every "sticky note" the current site has given you.


Further reading

— Nadeem 🍪

Comments