Advertisement

The web has a strange foundation: HTTP is stateless, meaning each request arrives with no memory of the ones before it. The server that just logged you in has, by default, forgotten you by your next click. And yet you stay logged in across a whole session. That illusion of memory is built from a small set of mechanisms — cookies, server sessions and tokens — and understanding them is essential to building or securing anything with a login.

Everything starts with the cookie, the humble tool that lets the browser carry a little identifying data from one request to the next.

Cookies: the browser's memory

A cookie is a small piece of data the server asks the browser to store and send back on every subsequent request to that site. That is the whole mechanism that defeats statelessness: the server sets a cookie, the browser returns it automatically, and suddenly the server can recognise a returning visitor. Cookies carry flags that matter enormously for security — HttpOnly hides them from JavaScript (blunting many theft attacks), Secure restricts them to HTTPS, and SameSite limits cross-site sending.

A cookie by itself is just a labelled note the browser carries. What that note contains — a session id or a token — is where the two main authentication styles diverge.

Advertisement

Server sessions: the id in the cookie

In the session approach, the server creates a record of your logged-in state in its own storage and hands the browser a cookie containing only a random session id. On each request the browser sends the id, the server looks up the matching record, and knows who you are. The sensitive data stays on the server; the cookie holds nothing but a meaningless key.

This is simple and secure to reason about, and logging someone out is easy — delete the server-side record. The cost is that the server must store and look up session state, which takes more thought to scale across many machines.

Tokens: the state travels with you

The token approach (often JWTs) flips it: the server signs a token that itself contains the identity and permissions, and the client sends it on each request. The server verifies the signature and trusts the contents without a lookup, which scales beautifully across many servers because no shared session store is needed. The trade-off is that tokens are hard to revoke before they expire, and storing them safely in the browser is genuinely tricky.

There is no universally right answer. Sessions are simple and easy to revoke; tokens are stateless and scale-friendly but demand careful handling. What matters is understanding that all of them are just ways to carry a little trustworthy memory across a protocol that, by design, remembers nothing.