HTTP Cookies

Session management and user tracking with HTTP cookies and security.

Introduction: Solving the Web's Memory Problem

One of the core design principles of the Hypertext Transfer Protocol (HTTP) is its stateless nature. A means that each request a server receives is treated as an completely independent event, with no memory of any previous requests from the same user. The server is like a librarian with short-term memory loss; every time you approach the desk, it's as if they've never seen you before.

This statelessness is a powerful feature for scalability. Any server can handle any request, which simplifies server design and allows for easy load balancing. However, it presents a major challenge for creating the interactive, personalized web experiences we now take for granted. How can an e-commerce site remember the items you've added to your shopping cart if every click on a new product page is a completely separate request? How does a social media site keep you logged in as you navigate between your feed and your profile?

The solution to this "amnesia" problem is the . Cookies are the web's memory, small pieces of data that allow a server to recognize a user across multiple requests, effectively creating a stateful session on top of a stateless protocol.

How Cookies Work: The Digital Handshake

The mechanism of cookies is an elegant extension of the HTTP request-response cycle, facilitated by two specific HTTP headers.

  1. Step 1: The Server Sets the Cookie

    When you visit a website for the first time, your browser sends a standard HTTP request. The server, upon receiving this request, can choose to create a unique identifier for your session. It then sends this identifier back to your browser as part of the response, using the Set-Cookie header.

    -- Server Response Header --
    HTTP/1.1 200 OK
    Content-Type: text/html
    Set-Cookie: sessionid=abf892kds9; Expires=Wed, 21 Oct 2026 07:28:00 GMT
  2. Step 2: The Browser Stores the Cookie

    Your browser receives this response and sees the Set-Cookie header. It then stores this small piece of data (the cookie, sessionid=abf892kds9) locally on your device, associating it with the website that sent it (e.g., example.com).

  3. Step 3: The Browser Returns the Cookie on Subsequent Requests

    From this point on, every time you make a new request to that same website (e.g., clicking a link or visiting another page), your browser will automatically include the stored cookie in the request, using the Cookie header.

    -- Client Request Header --
    GET /products/123 HTTP/1.1
    Host: www.example.com
    Cookie: sessionid=abf892kds9
  4. Step 4: The Server Recognizes the User

    The server receives this new request, reads the Cookie header, and sees the familiar session ID. It can then look up this ID in its database to retrieve your session data, such as your login status or the items in your shopping cart. This allows the server to provide a personalized response, effectively "remembering" you from your previous visit.

Types of Cookies: Understanding Their Purpose

Not all cookies are created equal. They can be classified based on their purpose, origin, and lifespan.

Based on Lifespan:

Session Cookies
These are temporary cookies. They exist only in your browser's temporary memory and are automatically deleted as soon as you close your web browser. They do not have an Expires or Max-Age attribute set by the server. Session cookies are essential for maintaining a user's session during a single visit, for example, by keeping a user logged in or remembering the contents of a shopping cart.
Persistent Cookies
These cookies have a specific expiration date, set by the server using the Expires or Max-Age attributes. They are stored on your device's hard drive and remain there until they expire or are manually deleted. Persistent cookies are used to remember user preferences over multiple visits, such as the selected language, theme, or the "Remember me" functionality on login pages.

Based on Origin:

First-Party Cookies
These are created and set directly by the website (domain) you are visiting. For example, when you log in to example.com, the session cookie set by example.com is a first-party cookie. They are generally considered essential for a website's core functionality.
Third-Party Cookies
These are created by domains other than the one you are currently visiting. They are typically used for cross-site tracking, advertising, and analytics. For example, if example.com embeds a "Like" button from a social media site or an ad from an ad network, that external service can set a cookie in your browser. This allows the third party to track your browsing habits across all the different websites that use its services. Due to privacy concerns, third-party cookies are being phased out by most major browsers.

Cookie Attributes: Fine-Grained Control

The Set-Cookie header can include several attributes that give developers fine-grained control over a cookie's behavior, which is crucial for both functionality and security.

Set-Cookie: name=value; Expires=date; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=Strict
Expires and Max-Age
As discussed, these make a cookie persistent. Expires specifies an absolute expiration date and time. Max-Age specifies the lifetime of the cookie in seconds from the time it is set, which is now the preferred method as it is not dependent on the client's clock being correct.
Domain
This attribute specifies which hosts are allowed to receive the cookie. If not specified, it defaults to the host of the origin server, and the cookie will not be sent to subdomains. If you set Domain=.example.com, the cookie will be sent to example.com and all of its subdomains, like api.example.com or blog.example.com.
Path
This attribute indicates a URL path that must exist in the requested URL in order for the browser to send the Cookie header. For instance, if you set Path=/admin, the cookie will only be sent for requests to pages within the `/admin` directory, like /admin/dashboard, but not to /home.
Secure
If this flag is present, the browser will only send the cookie over an encrypted HTTPS connection. This is a critical security attribute that prevents the cookie from being intercepted in plain text over an insecure HTTP connection. All cookies that contain sensitive information, especially session identifiers, must have the Secure flag.
HttpOnly
This is another crucial security attribute. When a cookie has the HttpOnly flag, it becomes inaccessible to client-side scripts (i.e., JavaScript running in the browser). This provides an important defense against attacks. If an attacker manages to inject a malicious script onto a webpage, that script will not be able to read or steal an HttpOnly cookie, protecting session tokens.
SameSite
This attribute provides a defense against attacks. It controls whether a browser sends a cookie with cross-site requests. It has three possible values:
  • Strict: The cookie will only be sent on requests originating from the same site. It will not be sent when the user navigates to the site from an external link.
  • Lax: The cookie will be sent for same-site requests and also for top-level navigations with safe HTTP methods (like GET) from external sites. This is the default in modern browsers. It allows users to stay logged in when clicking a link from an email, for example.
  • None: The cookie will be sent with all requests, both same-site and cross-site. This setting requires the Secure attribute and is typically used for third-party cookies.

Privacy, Security, and the Future of Cookies

While cookies are an essential part of how the modern web functions, their ability to track users across sites has raised significant privacy concerns. Third-party tracking cookies, in particular, have been criticized for enabling pervasive surveillance of users' online behavior by advertising and data-mining companies.

In response, privacy regulations like the GDPR in Europe and the CCPA in California have been enacted, requiring websites to obtain user consent before setting non-essential cookies. Furthermore, browser vendors are taking active steps to enhance user privacy:

  • Third-Party Cookie Deprecation: Google Chrome has announced plans to phase out support for third-party cookies entirely, following the lead of browsers like Safari and Firefox which already block them by default. This is a massive shift that is forcing the advertising industry to find new, more privacy-preserving technologies.
  • Intelligent Tracking Prevention: Browsers are implementing sophisticated algorithms to identify and restrict the capabilities of trackers, even those using first-party cookies, to limit cross-site tracking.

The web is moving towards a more private future. While first-party, functionally necessary cookies will remain a core part of web development, the era of widespread, opaque user tracking via third-party cookies is coming to an end, paving the way for new technologies within initiatives like Google's Privacy Sandbox.

Interactive cookie sandbox

Toggle attributes and test different request contexts to see when the browser stores or sends an HTTP cookie.

Set-Cookie header preview

This is what the application server returns in the response.

Set-Cookie: session_id=abc123; Path=/; Max-Age=1800; SameSite=Lax; Secure; HttpOnly

Cookie attributes

Secure (HTTPS only)

Keeps the cookie off HTTP connections.

HttpOnly

Stops document.cookie from exposing the cookie to scripts.

SameSite policy

Allows top-level GET navigation from other sites, but blocks background requests.

Request context

Connection uses HTTPS

Switch to simulate HTTPS vs. HTTP delivery.

Initial login response

Response

Server issues a session cookie after a successful sign-in.

200 OK from https://shop.local/login
Initiator: https://shop.localProtocol: HTTPS
Cookie stored
The cookie is stored only when the response arrives over HTTPS and the attributes are valid.

Why?

Everything complies with the current attributes.

JavaScript visibility

Blocked by HttpOnly — document.cookie cannot read this value.

    HTTP Cookies | Teleinf Edu