API Fundamentals
/Intermediate
Cookies
Definition
Small pieces of data sent by a web server and stored locally in the user's web browser. The browser automatically sends them back to the server with every subsequent request.
Explain Like I'm New
HTTP has 'amnesia' (it is stateless). If you log in, the server forgets who you are one second later. A Cookie is a nametag the server glues to your shirt. Every time you walk up to the server to ask for a new page, the server reads the nametag and says 'Ah, welcome back John.'
Real World Example
Adding items to an Amazon shopping cart without being logged in. Amazon stores your cart ID in a cookie. When you close the tab and return tomorrow, the browser sends the cookie back, and Amazon restores your cart.
Common Use Cases
- •Session management
- •Personalization
- •Tracking & Analytics
Terminal Output
bash / terminal
/* The Cookie Lifecycle */
// 1. Client sends a login request (No cookie yet)
POST /api/login
// 2. Server verifies password, and forces the browser to save a cookie
HTTP/1.1 200 OK
Set-Cookie: session_id=abc123xyz; HttpOnly; Secure; Max-Age=86400
// 3. User clicks on the /dashboard page 10 minutes later
// The browser AUTOMATICALLY attaches the Cookie header!
GET /api/dashboard
Cookie: session_id=abc123xyz
// 4. Server reads the cookie, looks up 'abc123xyz' in DB, returns private data.
Interview Questions
basic
- Does the client (browser) have to manually write code to send a cookie back to the server in a `fetch` request?
intermediate
- What happens if a user clears their browser cookies?