Cookie
A cookie is a small piece of data that a website stores in a user's browser, sent back to the server with every subsequent request to that site, commonly used for sessions, personalization, and tracking.
Definition
A cookie is a small piece of data that a website stores in a user's browser, sent back to the server with every subsequent request to that site, commonly used for sessions, personalization, and tracking.
Overview
Cookies were introduced in the mid-1990s to solve a fundamental problem of the web: HTTP is stateless, meaning a server has no memory of previous requests from the same browser. A server sets a cookie via a Set-Cookie response header, the browser stores it, and then automatically attaches it to every future request to that domain via the Cookie header — letting the server recognize returning users without any extra work on the client side. Cookies carry attributes that control their behavior and security: an expiration date (or 'session' cookies that vanish when the browser closes), a domain and path scope, and flags like HttpOnly (inaccessible to JavaScript, reducing XSS risk), Secure (only sent over HTTPS), and SameSite (restricting whether the cookie is sent on cross-site requests, which helps mitigate CSRF attacks). Modern browsers have also tightened default SameSite behavior and are progressively restricting third-party cookies, pushing sites toward first-party alternatives. Cookies remain the standard mechanism for authentication sessions because, unlike Local Storage, they are automatically included in requests by the browser and can be marked HttpOnly so client-side scripts can't read them, which matters for security-sensitive tokens. However, for non-sensitive client-side data that doesn't need to travel with every request, developers increasingly prefer Local Storage or IndexedDB, since cookies add overhead to every HTTP request and have a much smaller storage limit (typically around 4KB per cookie).
Key Concepts
- Automatically attached to every HTTP request to the domain that set it
- Configurable expiration — session cookies vs. persistent cookies with a set lifetime
- HttpOnly flag prevents JavaScript access, reducing exposure to XSS attacks
- Secure flag restricts transmission to HTTPS-only connections
- SameSite attribute controls cross-site sending, helping mitigate CSRF
- Small storage capacity, roughly 4KB per cookie
- Increasingly restricted for third-party tracking use cases by modern browsers