30 October 2026
Web cookies are one of those technologies that quietly shape every browsing session, yet most people only think about them when a consent banner interrupts their reading. The irony is hard to miss: the mechanism that keeps you logged in, preserves your shopping cart, and remembers your language preference is also the mechanism that fuels debates about privacy, surveillance, and consent. Understanding cookies properly means moving past the banner and grasping what actually happens between your browser and a server.
This guide takes you through cookies from first principles. Not just what they are, but why they exist, how they behave in practice, where developers get them wrong, and how the regulatory landscape has reshaped their design. By the end, you should be able to look at any cookie-related problem, whether you are debugging a session bug or evaluating a consent flow, and reason about it clearly.

This matters because cookies are often described as if they were programs or trackers in themselves. They are neither. A cookie is a delivery mechanism for state. The behavior comes from what the server does with the value it receives.
The reason cookies exist at all comes down to a fundamental property of HTTP: it is stateless. Each request arrives with no memory of previous requests. Without some way to carry context forward, a server could not tell whether two requests came from the same person, which would make login, carts, and personalization impossible. Cookies were the practical answer, introduced in the early days of the web and standardized over time.
- Domain determines which hosts receive the cookie. A cookie set for example.com is not automatically sent to api.example.com unless the domain attribute is configured to allow subdomains.
- Path narrows the cookie to specific URL paths, which is useful for isolating an admin panel from the rest of a site.
- Expires or Max-Age controls lifetime. Without either, the cookie is a session cookie and disappears when the browser closes.
- Secure restricts the cookie to HTTPS connections.
- HttpOnly hides the cookie from JavaScript, which is a critical defense against cross-site scripting.
- SameSite governs whether the cookie is sent on cross-site requests, and it has become one of the most important attributes in modern web security.
A cookie without careful attribute choices is not wrong by definition, but it is usually a liability waiting to surface.
Cookies solve this by giving the browser a way to present a token of continuity. When you log in, the server verifies your credentials once and then issues a cookie containing a session identifier. On subsequent requests, the browser presents that identifier, and the server looks it up in its own store to reconstruct who you are. The cookie itself does not contain your password or your identity in any readable form. It contains a reference.
This distinction between a reference and the actual data is central to good cookie design. Cookies travel over the network on every matching request, so they should be small and should never hold sensitive information directly. The server-side session store holds the sensitive part. When developers put user roles, email addresses, or permission flags directly into cookie values, they create problems: the data is exposed to the client, it inflates every request, and if the cookie is not signed or encrypted, it can be tampered with.

A first-party cookie is set by the domain shown in your address bar. When you visit a news site and it remembers your dark mode preference, that is first-party. These cookies are generally essential to how the site functions and are treated more leniently by browsers and regulators.
A third-party cookie is set by a domain other than the one you are visiting. If that news site embeds an advertising network's script, and the script sets a cookie, that cookie belongs to the ad network's domain. Because the same network appears across many sites, it can recognize your browser across all of them. This cross-site recognition is the foundation of behavioral advertising and also the reason third-party cookies have been under sustained pressure from browser vendors and regulators.
There is a second, often more useful taxonomy based on purpose:
- Strictly necessary cookies keep the site working: session management, load balancing, security tokens, checkout flows.
- Preference cookies remember choices like language, region, or display settings.
- Analytics cookies measure how people use the site.
- Marketing cookies support advertising, retargeting, and cross-site measurement.
These categories are not just academic. Consent rules in many jurisdictions treat them differently, and the practical advice for each differs sharply. Strictly necessary cookies generally do not require consent because the site cannot function without them. Marketing cookies almost always do.
A persistent cookie has an explicit expiry and survives restarts. Remember-me tokens, long-lived preferences, and consent records are typical uses. The trade-off is straightforward: persistence improves convenience and reduces friction, but it extends the exposure window if a token is stolen.
The right choice depends on the sensitivity of what the cookie represents. A "remember my language" preference can reasonably live for a year. A session token for a banking application should be short-lived and rotated. A consent record needs to persist long enough to honor the user's choice, which is why consent management platforms typically set cookies with multi-month lifetimes.
Ports are ignored in cookie scoping. A cookie set on `localhost:3000` is also sent to `localhost:8000`. This surprises people running multiple local services.
Cookie size limits are real. Browsers generally cap each cookie at around 4KB and limit the total number per domain. Exceeding those limits causes silent failures where older cookies get evicted. Stuffing a JWT with many claims into a cookie is a common cause of mysterious authentication bugs that only appear for users with large permission sets.
Cookies are also sent automatically. That convenience is the source of cross-site request forgery, where a malicious site triggers a request to your bank and the browser helpfully attaches your session cookie. The SameSite attribute exists precisely to control this. Setting `SameSite=Lax` allows the cookie on top-level navigations but blocks it on cross-site subrequests, which stops most CSRF vectors while preserving normal link-following behavior. `SameSite=Strict` is more aggressive and can break flows where users arrive from external links and expect to be logged in. `SameSite=None` requires `Secure` and reopens the cross-site surface, so it should be a deliberate choice, not a default.
Missing HttpOnly on session cookies. If a session cookie is readable by JavaScript, any cross-site scripting vulnerability becomes a session hijack. HttpOnly does not prevent XSS, but it removes the easiest path from XSS to account takeover. There is rarely a good reason for client-side code to read a session token.
Missing Secure. A cookie without the Secure flag can be sent over plain HTTP. On a network where an attacker can intercept traffic, that cookie is exposed. Modern browsers increasingly refuse to set insecure cookies on HTTPS pages, but relying on browser defaults is not a strategy.
Overly broad domain scope. Setting a cookie on the parent domain means every subdomain receives it, including subdomains you do not fully control. If a marketing team spins up a subdomain pointing at a third-party service, your session cookie may travel there. Scope cookies as narrowly as the application allows.
Long lifetimes without rotation. A session cookie that never expires and never rotates is a permanent key. Rotation on privilege changes, combined with reasonable absolute lifetimes, limits the damage from theft.
Sensitive data in cookie values. Even with encryption, putting sensitive data in cookies increases the attack surface. Keep cookies as opaque references and store the real data server-side.
There is also a subtler issue: cookie tossing and fixation. If an attacker can set a cookie for your domain, they may be able to influence session behavior. Defenses include regenerating session identifiers at login, validating that cookies match expected formats, and using prefixes like `__Host-` and `__Secure-` that browsers enforce, which prevents subdomains from overwriting cookies set at the host level.
This produced the consent banners that now dominate the web. The quality of those implementations varies enormously. A well-built consent flow:
- Presents categories clearly and does not pre-select non-essential options.
- Makes rejecting as easy as accepting.
- Records the choice with a timestamp and version of the policy.
- Blocks non-essential scripts until consent is given.
- Allows withdrawal of consent later.
A poorly built flow loads tracking scripts before the user interacts with the banner, which defeats the purpose. It also creates legal exposure. The technical lesson is that consent must be enforced at the point of script execution, not merely displayed in a dialog.
Consent management platforms handle this by intercepting script loading and gating it on stored preferences. The preference itself must be stored somewhere, which is why consent platforms set their own cookies. Those cookies are usually classified as strictly necessary because they record the user's decision, though the classification is not universal and depends on jurisdiction.
localStorage persists data with no expiry and is not sent automatically with requests. That makes it convenient for preferences but dangerous for tokens, because any XSS can read it. Many security teams prefer HttpOnly cookies for session tokens precisely because localStorage offers no such protection.
sessionStorage is scoped to a tab and cleared when the tab closes. Useful for multi-step form state, not for authentication.
IndexedDB handles larger structured data but is overkill for simple state.
For authentication specifically, there is an ongoing debate between cookie-based sessions and token-based approaches with Authorization headers. Cookies win on simplicity and on HttpOnly protection. Header-based tokens win on cross-domain flexibility and on avoiding CSRF concerns, at the cost of requiring careful storage. Many modern architectures use a hybrid: a short-lived access token in memory, a refresh token in an HttpOnly cookie, and CSRF protection layered on top. None of these choices is universally correct. The decision should follow from your threat model, your domain structure, and your team's ability to maintain the implementation correctly.
"Cookies are viruses." They are not. They are text. The risk comes from what servers do with them, not from the cookie itself.
"Deleting cookies logs you out everywhere." It logs you out of sites that rely on cookies for sessions, which is most of them, but it does not affect server-side state. Some sites will still recognize your device through other signals, which is a separate topic.
"Incognito mode blocks cookies." It does not. It isolates them and clears them when the session ends. Sites still set cookies within the private session.
"Third-party cookies are already gone." Some browsers have restricted them, and the timeline has shifted repeatedly. The practical reality in 2025 is a patchwork: some environments block them, others allow them with restrictions, and many sites still depend on them. Assuming they are unavailable and designing accordingly is the safer engineering posture, but claiming they are universally dead overstates the situation.
"Consent banners mean the site is compliant." A banner is a UI element. Compliance depends on whether the underlying data flows actually honor the user's choice.
Start by inventorying every cookie your application sets, including those set by third-party scripts. You cannot secure or classify what you have not catalogued. Browser developer tools show cookies per domain, and most frameworks have middleware that can log them.
Then classify each cookie by purpose and set attributes accordingly. Session cookies should be HttpOnly, Secure, and SameSite=Lax or Strict. Preference cookies can be less restrictive but should still be scoped narrowly. Marketing cookies should be gated behind consent and documented.
Keep cookie values small and opaque. If you find yourself encoding user profiles into a cookie, move that data server-side.
Test across subdomains and environments. Cookie bugs frequently appear only in staging or production because domain and path scoping differ from local development.
Finally, plan for a world with fewer third-party cookies. First-party data strategies, server-side tagging, and privacy-preserving measurement are not just compliance measures; they are more durable architectures. Sites that depend heavily on third-party cookies for core functionality are exposed to browser policy changes they do not control.
The useful mental model is this: a cookie is a note the server asks the browser to carry. Everything else, security, privacy, performance, compliance, follows from how that note is written, where it is allowed to travel, how long it lives, and what the server does when it reads it. Get those details right, and cookies become a reliable, well-understood tool. Get them wrong, and you inherit bugs, breaches, and regulatory headaches that are entirely avoidable.
all images in this post were generated using AI tools
Category:
Technology GuidesAuthor:
Kira Sanders