How Sessions Work
Objectives
By the end of this lesson, you should be able to:
- Explain what a session is, and where it actually lives
- Explain the role a cookie plays in session-based authentication
- Trace the full request cycle from login to a protected request
💡 Why this matters: Module 1 built a way to verify a password once. A real application needs to remember that a user is logged in across many separate requests, HTTP itself has no memory between requests, sessions are the traditional way around that.
HTTP Has No Memory
Every HTTP request is independent, the server handling a GET /api/v1/me request has no built-in way to know it’s the same browser that logged in three requests ago. Something has to carry that identity forward, request to request.
What a Session Actually Is
A session is a small piece of data, stored on the server, tied to one specific logged-in user. When a user logs in successfully, the server:
- Creates a session, and stores something in it (commonly just the user’s ID).
- Generates a unique session ID for that session.
- Sends that session ID back to the browser in a cookie.
On every later request, the browser automatically sends that cookie back. The server looks up the session by the ID in the cookie, finds the stored user ID, and knows exactly who’s making the request, no password re-entry needed.
Where Session Data Lives
The actual session data (the user’s ID, and anything else stored in it) lives on the server, not in the cookie. The cookie only holds the session ID, a reference, not the data itself. This matters for two reasons: the data itself never travels back and forth on every request, and a session can be instantly invalidated server-side (at logout, for example) without needing to do anything on the client at all.
The Full Cycle
1. POST /api/v1/auth/login (email + password)
→ server verifies credentials, creates a session, sends back a cookie
2. GET /api/v1/me (browser sends the cookie automatically)
→ server looks up the session from the cookie, finds the user, responds
3. POST /api/v1/auth/logout
→ server destroys the session
→ the same cookie no longer matches anything
Try It
- Explain, in your own words, why HTTP being “stateless” is the exact problem sessions solve.
- Explain what’s actually stored inside the cookie itself, versus what’s stored on the server.
- Walk through, in words, what happens on the server the moment a session is destroyed at logout, and why the old cookie stops working.
Recap
- HTTP requests are independent, sessions are how a server remembers a logged-in user across many separate requests.
- A session’s data lives on the server, the cookie only carries a session ID, a reference to that data.
- Login creates a session and sends its ID in a cookie, later requests send that cookie automatically, logout destroys the session.
Next lesson: wiring this into a real Express app with express-session.