Wesloo
All topicsTopics

Web technologies

How Do Web Cookies Work? A Practical Guide

Short answer

A web cookie is a small piece of data a server sends to a browser, which the browser stores and returns with later requests to the same site. Cookies let stateless HTTP remember logins, preferences, and activity, but they also raise privacy and security concerns.

Key points

  • Servers send cookies with Set-Cookie; browsers return them with Cookie.
  • Session cookies end when the browser closes; persistent cookies have an expiry date.
  • First-party cookies come from the site you visit; third-party cookies come from embedded domains.
  • Secure, HttpOnly, and SameSite attributes reduce common cookie risks.
  • Modern storage APIs are often better for large client-side data.

How do web cookies work?

How do web cookies work? A web server sends a small record of data to your browser, usually in an HTTP response. The browser stores that record and sends it back with later requests to the same site, allowing the server to recognize a returning browser or remember choices.

HTTP is stateless, meaning each request is independent. Cookies add continuity by carrying a small identifier or preference value between requests. A site might store a session ID, language choice, or consent flag, then read it on the next page load.

When a browser requests a page, the server can include a Set-Cookie header in its response. That header contains the cookie name, value, and attributes. The browser parses it, applies scope and security rules, and stores it in its cookie store.

On the next request to a matching domain and path, the browser adds a Cookie header containing the stored name-value pairs. The server reads that header and uses the values to continue a session or apply preferences. If the cookie has expired or been deleted, it is not sent.

This round trip is what makes a stateless protocol feel continuous. A login flow can issue a session identifier after credentials are checked, then require that identifier on protected pages.

A cookie is a name-value pair plus attributes. The name and value hold the data, while attributes tell the browser when and where to send it.

  • Name and value: the stored data, such as session=abc123.
  • Domain and Path: the scope that decides which requests include the cookie.
  • Expires or Max-Age: the lifetime. Without either, the cookie is a session cookie.
  • Secure: the cookie is sent only over HTTPS.
  • HttpOnly: JavaScript cannot read the cookie through document.cookie.
  • SameSite: controls whether the cookie is sent with cross-site requests.

Because cookies are sent with every matching request, large or numerous cookies can slow page loads, especially on mobile networks. Browsers also cap cookie size and count, commonly around 4 KB per cookie and hundreds per domain.

Scope: domain and path

The Domain attribute controls which hosts receive the cookie. If it is omitted, the cookie is host-only and is sent only to the exact origin that set it. If a domain is specified, subdomains may also receive it, depending on browser rules.

The Path attribute narrows delivery to URLs beginning with a given path. A cookie set with Path=/account is not sent to /blog. Together, domain and path prevent unnecessary data from being attached to unrelated requests.

Lifetime: session and persistent cookies

Session cookies have no expiry date. They live in memory while the browser is open and are removed when the browser closes or the session becomes inactive. Sites use them to keep a login or shopping cart active during a visit.

Persistent cookies include an expiry date or maximum age. They are written to disk and remain for a set period, often less than six months in common examples, so a site can remember a preference or recognize a returning device later.

First-party, third-party, and supercookies

First-party cookies are set by the domain in the address bar. They usually support core features such as login state, language settings, and site analytics.

Third-party cookies are set by domains embedded in a page, such as ad networks, analytics providers, or social widgets. They can track browsing across sites and build profiles for targeted advertising. A page you visit may include resources from several other domains, and each of those domains can set its own cookies.

A supercookie is a special case whose origin is a top-level domain or public suffix, such as .com or .co.uk, rather than a single site. Ordinary cookies are tied to a specific domain name.

Common uses

Cookies are widely used for authentication. When you open a login page, the server may send a cookie containing a unique session identifier. After you authenticate, the server links that identifier to your account and grants access on later requests.

They also store preferences such as theme, language, or region. Some sites use them for analytics, measuring visits and feature use. In the early web, cookies were often used for general client-side storage; modern APIs such as Web Storage and IndexedDB are now recommended for larger data.

When building these features, teams choose languages and frameworks that affect how cookies are parsed, signed, and validated. For broader selection criteria, see choose programming language: a practical guide.

Security attributes and threats

Cookie values are visible to the end user by default and can be changed. If an attacker steals a session ID, they may be able to set a cookie that makes them appear logged in as another user. This is why session identifiers need protection in transit and in storage.

Secure cookies are sent only over HTTPS, where end-to-end encryption protects the request. A network attacker or proxy cannot read the encrypted bytes. HttpOnly cookies are not exposed to JavaScript, which reduces the impact of cross-site scripting. SameSite limits cross-site sending and helps reduce cross-site request forgery.

Cookie theft and session hijacking are documented risks for sites that rely solely on HTTP cookies for identification. Secure transport, short session lifetimes, and server-side validation reduce that risk.

Privacy and user control

Third-party cookies raise privacy concerns because they can follow activity across sites. Browser settings, private browsing, and cookie deletion tools give users control. On Windows, cookie files are often found under a browser-specific folder in AppData; on macOS, they are often under ~/Library/Cookies. Exact locations vary by browser and operating system.

You can view stored cookies in browser developer tools, such as the Storage inspector in Firefox or the Application panel in Chrome. From there you can delete individual cookies or clear all site data.

Privacy-focused users may also want to review account-level tracking. For example, Delete Facebook Account Permanently: Complete Guide covers removing a social account, while Organize Email Inbox with Filters and Labels shows another way to reduce unwanted automated messages.

Performance and storage limits

Cookies are sent with every matching request, so they can worsen performance on slow connections. Keeping values small and limiting the number of cookies helps. Browser limits on cookie count and size still apply.

Storage APIs can hold more data and do not attach it to every request automatically. That difference can make them more secure in some respects, because they are not exposed to network cookie sniffing in the same way.

Alternatives and when to use them

Use cookies when the server needs a small value on every request, such as a session ID or CSRF token. Use Web Storage or IndexedDB for larger client-side data that does not need to travel to the server. Cache APIs and service workers can also reduce repeated network requests.

For developers, the right choice depends on data size, sensitivity, and whether the server needs the value. Signed or encrypted cookie values, rotation of session identifiers, and strict attribute settings are common safeguards.

Managing cookies as a user or developer

Users can block third-party cookies, clear cookies on exit, or use browser extensions that limit tracking. Developers should set the narrowest practical domain and path, use Secure and HttpOnly where appropriate, and choose SameSite values based on whether cross-site requests are needed.

Inspecting cookies during development helps catch scope mistakes. If a cookie is missing, check its domain, path, expiry, Secure flag, and SameSite setting against the request URL.

Questions people also ask

Are web cookies dangerous?

Cookies are not dangerous by themselves, but stolen session cookies can let an attacker impersonate a user. Using HTTPS, HttpOnly, and short session lifetimes reduces that risk.

What is the difference between session and persistent cookies?

Session cookies have no expiry date and are removed when the browser closes. Persistent cookies include an expiry date or maximum age and remain stored for a set period.

Can I delete cookies?

Yes. Browser settings and developer tools let you delete individual cookies or clear all site data. Private browsing modes also limit how long cookies persist.

Do cookies store passwords?

They should not store raw passwords. A safer pattern is to store a random session identifier and keep account credentials on the server.

What does HttpOnly mean?

An HttpOnly cookie cannot be read by JavaScript through document.cookie. This reduces the chance that a cross-site scripting attack steals the cookie.

Related pages

  • Client vs Server Rendering: Architecture and Performance

    Client-side rendering generates HTML directly inside the user browser via downloaded JavaScript, whereas server-side rendering compiles the full HTML document on the origin or edge server prior to transmission. This core difference shifts computational burdens between client hardware and cloud infrastructure, altering First Contentful Paint times, search indexing reliability, and hosting costs. Teams select between them based on content volatility, interaction requirements, and performance objectives.

  • How Does Browser Cache Work? A Practical Guide

    A browser cache stores local copies of web resources so repeat visits skip downloads. Servers set freshness with Cache-Control, and browsers validate or evict entries when space runs low.

  • What is WebSocket and how it works?

    WebSocket is a protocol for bidirectional, low-latency communication over a persistent connection between a client and a server. It begins with an HTTP handshake and then stays open so either side can send messages without creating a new request each time. Use it when an application needs frequent real-time updates; use ordinary HTTP when request-response traffic is enough.

  • What is a REST API vs API? A Practical Guide

    An API is a contract that lets software systems exchange requests and responses. A REST API is one kind of API that uses HTTP methods and resource-based URLs to manage data, usually with JSON. All REST APIs are APIs, but many APIs use other protocols or styles.

  • What is GraphQL API? A Practical Guide

    A GraphQL API is a query language and runtime for APIs that lets a client request only the fields it needs, including related data, in one operation. It is backed by a strongly typed schema that defines types, fields, and allowed operations. Clients control the shape of the response, while the server resolves data from its sources.

  • What is CORS in IT? Browser security explained

    Cross-Origin Resource Sharing (CORS) is a browser security mechanism that lets a server declare which other origins may read its responses. It extends the same-origin policy so trusted sites can use APIs and resources hosted elsewhere. Without the right headers, a script's cross-origin request fails in the browser.

How this page was prepared

Before writing, the topic was researched in the sources below. The page then passed automatic quality checks.

Report a mistake on this page