🍪 Cookies & Sessions: Classic Cookie-Based Authentication
Context: In the previous module you learned JWT-based authentication. Now we explore the other major pattern — server-side sessions with cookies — so you can choose the right tool for each project.
1. How HTTP Cookies Work
Cookies are small pieces of data stored in a user's browser. The server sends a Set-Cookie header in the HTTP response; once stored, cookies are automatically attached by the browser to every subsequent request to that domain — no manual JavaScript needed.
The Cookie Lifecycle
// 1. Server sends Set-Cookie in the response
HTTP/1.1 200 OK
Set-Cookie: connect.sid=s%3Aabc123.sig; Path=/; HttpOnly; Secure; SameSite=Lax
// 2. Browser stores the cookie
// 3. Browser automatically attaches it to EVERY request to this domain
GET /dashboard HTTP/1.1
Host: myapp.com
Cookie: connect.sid=s%3Aabc123.sig