Sessions and Cookies
Implement login with server-side sessions and secure cookie settings, the classic and still excellent approach.
Intermediate · about 5 hours · difficulty 3/5
Learn first: HTTP in Depth
HTTP is stateless, so after a user logs in the server needs a way to recognize them on the next request. The classic approach: create a session (a record on the server, often in Redis or the database), and send the browser a cookie containing a random, unguessable session id. The browser sends it back automatically on each request.
Cookie attributes that matter
HttpOnly: JavaScript cannot read the cookie, limiting damage from XSS.Secure: only sent over HTTPS.SameSite=LaxorStrict: not sent on most cross-site requests, a strong defense against CSRF.Max-Age/Expires,PathandDomain: control lifetime and scope.
Session lifecycle
- Regenerate the session id at login to prevent session fixation.
- Expire sessions after inactivity and absolutely after some maximum.
- On logout, delete the server-side session, not just the cookie.
Why sessions are a great default
They are simple, revocable instantly (delete the record), and keep sensitive data on the server. For a typical web app with its own frontend, sessions are often a better choice than JWTs.
Pitfalls
- Storing sessions in process memory, which breaks as soon as you run two instances.
- Using cookies for cross-site APIs without understanding CORS credentials and SameSite.
You are ready to move on when you can build login and logout with Redis-backed sessions and explain each cookie attribute you set.
Key concepts
- Stateful sessions
- HttpOnly, Secure, SameSite
- Session stores (Redis, database)
- Session fixation and regeneration
- CSRF protection
- Remember-me and expiry
Mini project
Add email and password login to an API using Redis-backed sessions, with session regeneration at login, an idle timeout and a logout-everywhere endpoint.
Check yourself
How does SameSite=Lax help against CSRF, and what cases does it not cover?