Session

Key points

  • A session is a mechanism for temporarily remembering per-user state on the server side, giving the browser only a short identifier called a "session ID."
  • Cookies are usually used to carry the session ID back and forth. Attributes like HttpOnly and Secure are essential for protecting it from interception and script-based theft.
  • When running multiple servers, the actual session data needs to live in a shared external store, such as Redis.
  • Choosing between sessions and stateless "token authentication" (like JWT) has become an important design decision in recent years.

Recap: HTTP doesn't remember state

HTTP has a property called "stateless," meaning the relationship resets every time a request finishes. A server generally doesn't remember "who did what a moment ago."

1st
request
No memory of it
2nd
request

But in real web apps, there's a common need to "stay logged in while browsing multiple pages." Sessions were created to solve exactly this problem.

What is a session?

A session is a mechanism that temporarily stores per-user state in server-side memory or a database (called a "session store").

The browser is only given a short string called a "session ID," which points to that stored state. The key point is that the actual data itself stays on the server side.

Server
(session store)
Issues only the ID
Browser holds
only the ID

Teacher Pochi's hintThis is a lot like a hospital reception number. All of your medical records are managed by the hospital, and the only thing you carry around is a "numbered ticket." Show the number, and the hospital instantly pulls up your chart.

How session IDs are issued and matched

On the first visit, the server issues a session ID. On every request after that, the browser sends that ID back, and this is how "identity confirmation" happens.

First visit:
issue an ID
Browser
stores the ID
Sends the ID
next time
Server matches
by ID

Teacher Pochi's hintA session works a lot like a coin locker at a train station. Your luggage (the actual data) stays inside the locker, and all you carry around is the "key (number)." Just show the key, and the locker gives you back your own belongings — you never have to carry the luggage itself around with you.

Cookies carry the session ID

A session ID is usually carried inside a cookie. On the first response, the server hands it over with a "Set-Cookie" header; from then on, the browser automatically sends it back with a "Cookie" header on every request.

Server
Set-Cookie:
session_id=abc123
Browser
stores it
Cookie:
session_id=abc123
Server matches
by ID

The cookie carrying a session ID should always have HttpOnly (unreadable from JavaScript) and Secure (only sent over HTTPS) attached. Drop either one, and the session hijacking risk we'll cover shortly rises sharply. The cookie mechanism itself is covered in more depth in the dedicated cookie topic.

Where session data actually lives

Where you store session data (the session store) depends on your server setup — this choice matters especially once you scale to multiple servers.

💻 In-server memory Simple to implement, and fine for a single server Add more servers and another instance won't recognize the ID, causing inconsistencies
🗃️ External store (e.g. Redis) Every server can reference the same shared session store Sessions survive restarts more reliably — a standard setup for large-scale services

You can also work around this with a load balancer setting that always sends the same user to the same server ("sticky sessions"), but that approach loses sessions more easily if that particular server goes down.

Session security risks and defenses

A session ID is essentially the "key to identity confirmation" — if it's stolen or abused, it can lead to impersonation. The main risks and defenses are:

Session hijackingThe ID gets stolen via eavesdropping or XSS, enabling impersonation.
Defense: HTTPS + HttpOnly / SecureBlocks both interception and script-based reads.
Session fixationAn attacker plants an ID for the victim to use, then hijacks it later.
Defense: reissue the ID on successful loginAlways change the session ID around the moment of authentication.

Teacher Pochi's hintLosing a coin locker key, or having someone swap it out for a fake, would be a disaster. A session ID needs the same kind of care — protecting the "key" itself is what matters most.

Session timeouts

A session doesn't stay valid forever. There's a mechanism called a "session timeout" that automatically invalidates it after a period of inactivity.

ActiveSession is valid. Login state is maintained.
Time elapsedApproaching timeout. A warning may be shown.
Timed outSession expired. Re-login required.

This is also a security measure — it reduces the risk of a third party hijacking a session while you're away from your desk. Banking sites in particular tend to set especially short timeout periods.

Common uses for sessions

Beyond keeping users logged in, sessions power a range of web app features — and they're also put to work in digital marketing and marketing automation (MA) tools.

🔑 Application-level uses Staying logged in: no need to resend credentials with every request Shopping carts and in-progress forms: holding cart contents before signup, or state across a multi-step wizard Flash messages and CSRF tokens: a one-time notice right after a redirect, or a token stored to guard against forged requests
📈 Digital marketing and MA tools Recording an anonymous visitor's behavior for the session, then linking it to a named "lead" once they submit a form Holding onto the traffic source (e.g. UTM parameters) from an ad or email for the session, so a later conversion gets attributed to the right campaign Tailoring the content or offer shown based on the pages a visitor viewed earlier in the same session (personalization)

Teacher Pochi's hintThe "session" that MA tools track works on the same idea we've already covered — it also gets cut off after a period of inactivity. That cutoff is exactly what makes it possible to trace "which ad brought them in, what they looked at, and whether they ultimately reached out" as one connected story.

A stateless alternative: token authentication

Session IDs keep state on the server side ("stateful"). In recent years, an approach that keeps no server-side state at all ("stateless") has also become common — token authentication, like JWT, is the leading example.

🎫 Session ID (stateful) Requires a session store on the server side The server can forcibly invalidate a session at any time
🔏 Token (stateless) Just verify a signature — no server-side storage needed Scales easily across more servers, but individually revoking an issued token is hard

Neither approach is universally "correct" — real systems choose between them, or combine both, based on their requirements.

Summary

A session is a mechanism that temporarily stores per-user state on the server side while giving the browser only a lightweight ID, making "continuous interaction" possible. Cookies carry that ID, and attributes like HttpOnly and Secure, reissuing the ID on login, and appropriate timeouts all form the foundation for preventing impersonation. Running multiple servers usually means storing sessions in an external store, and choosing between that and stateless token authentication like JWT is an important design decision.

Related topics:

🏠 Back to top