What is a cookie?
A cookie is a small piece of data that a server stores in the client's browser, which the browser then automatically sends back to the server on subsequent requests.
In simple terms: a cookie is a way to "remember" a user between HTTP requests.
Why cookies are needed
HTTP is a stateless protocol, meaning:
- the server does not remember the user
- each request is like a new one
Cookies are needed to:
- keep authorization
- remember the user's settings
- store a session identifier
- track state (a cart, a language, a theme)
Without cookies, many sites would be very inconvenient.
How cookies work (step by step)
- The client sends an HTTP request
- The server responds and tells the browser:
"Save this data"
- The browser stores the cookie
- On every subsequent request to this site, the browser automatically attaches the cookie
All of this happens transparently for the user.
What is usually stored in a cookie
Cookies do not store large amounts of data, they usually hold:
- a session identifier
- an authorization token
- interface settings
- flags and states
Passwords in plain form must not be stored in a cookie.
Key properties of cookies
Tied to a site
Cookies:
- are sent only to the domain that set them
- do not "travel" between sites
Limited size
- usually up to ~4 KB
- cookies are not suited for large amounts of data
Lifetime
Cookies can be:
- session-based (deleted when the browser closes)
- persistent (stored until a set date)
Cookies and security
There are special flags:
- Secure - the cookie is sent only over HTTPS
- HttpOnly - inaccessible from JavaScript
- SameSite - protection against CSRF attacks
In interviews, this is often a plus for the answer.
Real-life example
A cookie is like a coat-check ticket:
- you're given a number
- you show it every time
- it's how you're "recognized"
Short answer for an interview
Remember this wording:
A cookie is a small piece of data that a server stores in the client's browser and that is automatically sent to the server on subsequent HTTP requests to store state and identify the user.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.