Cookie
A small piece of data that a browser stores and automatically sends with matching HTTP requests. It lets a website remember things such as your preferred language or the fact that you signed in.
Also known as: куки
What problem does a cookie solve?
An HTTP request does not automatically tell the server who made the previous one. After you sign in, the server can give your browser a cookie containing a session ID. When you open your account page, the browser sends that ID back and the server uses it to look up your session. The cookie does not need to contain your password or your profile. Cookies can also carry small preferences the server needs, such as which language to render a page in.
Follow the headers
A server sets a cookie with the Set-Cookie response header. If the browser accepts it, the browser stores the name, value, and attributes. On a later request, the browser checks which cookies apply and puts their name–value pairs in the Cookie request header. It does not send the attributes back.
Set-Cookie: session_id=abc123; Path=/; Secure; HttpOnly; SameSite=Lax
For example, a later HTTPS request to /account on the same host can carry Cookie: session_id=abc123. The value here is illustrative: a real session ID must be unpredictable. When a user signs out, the server should invalidate the session, not just ask the browser to remove the cookie.
What controls when a cookie is sent?
- Scope: Without
Domain, a cookie is limited to the host that set it. With a valid parentDomain, it can also apply to subdomains.Pathfilters requests by URL path; it is not a security boundary. - Lifetime:
Max-Agegives the lifetime in seconds;Expiresspecifies an expiration date. Without either, the cookie is a session cookie, but browser session restore can bring it back. - Transport and script access:
Securerestricts transmission to secure connections.HttpOnlykeeps the value out ofdocument.cookie, but the browser can still attach the cookie to a matching request made by JavaScript. - Cross-site requests:
SameSite=Laxgenerally allows the cookie on a top-level navigation using a safe method, such as following a link, but not on a typical cross-sitefetch.SameSite=NonerequiresSecureand does not override browser restrictions on third-party cookies.
Common interview pitfalls
Cookies are not just another spelling of localStorage. A browser does not automatically send localStorage values to the server, so it can be a better fit for a preference used only by page code. For a cookie that never shows up on the server, first check the response in DevTools to see whether the browser accepted Set-Cookie. Then inspect the next request for Cookie. That separates a storage problem from a sending problem and narrows the list of settings to check.