Cookie
What is it?
A cookie is a small piece of data a website stores in your browser and sends back on future requests, so the site can remember things about you.
Explain like I'm 5
Why was it created?
HTTP forgets you between requests. Cookies were created so sites could remember state — like being logged in — across visits.
Where is it used?
- Keeping users logged in (session IDs)
- Remembering preferences
- Shopping carts
- Analytics and tracking
Why should developers care?
Cookies power logins, preferences, and tracking, and come with privacy and security rules every web developer must handle.
How does it work?
The server sends a Set-Cookie header; the browser stores the cookie and automatically includes it on later requests to that site. Cookies can carry flags for expiry, security (HttpOnly, Secure), and cross-site behavior (SameSite).
Real-world example
After you log in, the server sets a cookie holding your session ID; your browser sends it on each request so you stay logged in.
Common use cases
- Session and login state
- User preferences
- Carts and personalization
- Tracking and analytics
Advantages
- Automatically sent by the browser
- Persist across visits
- Simple and universal
- Security flags available
Disadvantages
- Privacy concerns
- Can be stolen if not secured
- Size limits
- Subject to regulations and consent rules
When should you use it?
When the server needs to remember per-user state across requests, especially for sessions.
When should you avoid it?
For larger client-only data that never needs to go to the server (use local storage instead).
Alternatives
Related terms
Interview questions
Beginner
- What is a cookie?
- What is a cookie commonly used for?
Intermediate
- What do the HttpOnly and Secure flags do?
- What is SameSite?
Senior
- How do you protect session cookies from theft (XSS/CSRF)?
- How do cookies differ from local storage in security?
Common misconceptions
- "Cookies are programs that can harm your computer" — they're just small data files, not executable code.
- "Cookies and local storage are interchangeable" — cookies are auto-sent to the server; local storage stays in the browser.
Fun facts
- The HttpOnly flag hides a cookie from JavaScript to reduce theft via cross-site scripting.
- SameSite settings help defend against cross-site request forgery.
Timeline
- 1994 — Cookies introduced in early web browsers
Learning resources
Quick summary
A cookie is small browser-stored data sent back to a site on each request, used for sessions, preferences, and tracking — with security flags that matter.
Cheat sheet
- Small data stored in the browser
- Auto-sent to the server
- Powers sessions and preferences
- Secure with HttpOnly/Secure/SameSite