Auth & sessionsAdvanced5h

Sessions & cookies.

Keeping a user logged in across requests, securely.

What are sessions and cookies?

HTTP is stateless, so the server needs a way to remember a logged-in user between requests. A session stores that state (server-side or in a signed token), and a cookie carries the identifier on every request automatically. This is the machinery behind staying logged in.

Why it matters

Sessions and cookies are where a lot of auth security lives — get the cookie flags or storage wrong and you open the door to session theft or CSRF. As a full-stack developer you configure both the server's session handling and the cookie, so you own these decisions directly.

What to learn

  • Server-side sessions versus stateless tokens
  • Cookie attributes: httpOnly, Secure, SameSite
  • Why httpOnly cookies resist XSS token theft
  • CSRF and how SameSite and tokens defend against it
  • Session expiry and renewal
  • Storing session state (memory, Redis, database)
  • Logout and invalidation

Common pitfall

Storing a session token in localStorage so client JavaScript can read it. That makes it stealable by any XSS, and XSS is common. An httpOnly cookie cannot be read by JavaScript, so a script injection cannot exfiltrate the session. Prefer httpOnly, Secure, SameSite cookies for session credentials.

Resources

Primary (free):

Practice

Set up session handling with an httpOnly, Secure, SameSite cookie. Confirm the cookie is sent automatically on requests and cannot be read from client JavaScript. Implement logout that invalidates the session server-side. Done when the session survives reloads and is gone after logout.

Outcomes

  • Choose between server sessions and stateless tokens.
  • Set secure cookie attributes correctly.
  • Defend against XSS token theft and CSRF.
  • Handle session expiry, renewal, and logout.
Back to Full-Stack roadmap