TidyURLs
Go to Tools
BLOG
The TidyURLsJournal

Practical guides, tutorials, and insights about URLs, SEO, web development, and online marketing. Learn, troubleshoot, and get the most of the web.

Back to the Journal
TidyURLs Journal

Browser Cookies Explained: Sessions, Preferences, and Tracking

Practical insights, clear explanations, and useful ideas for understanding the web.

October 25, 20269 min read6 topics
Browser Cookies Explained: Sessions, Preferences, and Tracking
Explore the details
#browser cookies#web development#HTTP#session management#web security#privacy
October 25, 20269 min read

Browser cookies are small pieces of data that help websites remember a visitor between HTTP requests. They can keep a user signed in, save a preference, or help measure activity across pages. Because browsers attach matching cookies to requests automatically, cookie scope and security settings matter as much as the data stored in them.

This guide explains how cookies are set and sent, how session cookies differ from persistent cookies, what Secure, HttpOnly, and SameSite do, and how cookies compare with local storage and URL parameters.

Key takeaways

  • A server can set a cookie with the Set-Cookie response header; browsers send matching cookies back in a Cookie request header.
  • Domain, Path, and expiry settings determine where and for how long a cookie applies.
  • Secure, HttpOnly, and SameSite reduce particular risks, but none replaces sound session management or other security controls.
  • Cookies are sent with matching requests; local storage is not sent automatically, and URL parameters travel as part of the URL.
  • Browser privacy settings and third-party cookie policies affect tracking, so behavior can differ between browsers and configurations.

How browser cookies work

HTTP requests are independent by default: a web server does not automatically know that two requests came from the same browser. Cookies provide one way to carry a small identifier or preference between requests.

A server sends a Set-Cookie header in an HTTP response. The browser decides whether to store it according to the cookie's attributes and its own policies. On later requests that match the cookie's scope, the browser includes the cookie in a Cookie request header. JavaScript can also read and write many cookies through document.cookie, unless a cookie is marked HttpOnly.

For example, a response might contain:

Set-Cookie: __Host-session=opaque-value; Path=/; Max-Age=1800; Secure; HttpOnly; SameSite=Lax

The value shown is illustrative. A real session identifier should be unpredictable and should not contain sensitive user data. Cookie values are not inherently encrypted; use HTTPS to protect them in transit.

Cookie scope: Domain and Path

Cookie scope determines which requests receive a cookie.

  • Host-only cookies: If the server omits the Domain attribute, the cookie is generally limited to the host that set it. This is a good default for many application cookies.
  • Domain cookies: A Domain attribute can make a cookie available to the specified domain and its subdomains, subject to browser rules. Broader scope means more hosts can receive the value, so do not set it more broadly than necessary.
  • Path: The Path attribute limits which URL paths receive a cookie. It is useful for organizing behavior, but it is not a reliable security boundary between applications on the same host.

For example, Path=/account limits when a cookie is sent based on the request path. It does not protect the cookie from a compromised application running elsewhere on the same origin.

If you are learning how a URL is divided into its components, a URL parser can help inspect a URL's host and path. Parsing a URL is useful for understanding its structure, but it does not configure or secure cookies.

Expiry: session and persistent cookies

A cookie with Max-Age or Expires is persistent: the browser can retain it until its expiry, subject to user settings and browser storage policies. If both attributes are present, Max-Age takes precedence in browsers that follow the standard behavior.

A cookie without either attribute is usually called a session cookie. It is intended to last for the browser session, but the practical end of a session can vary. For example, browser session restoration may preserve session cookies when a user reopens a previous session. Do not treat session-cookie expiry as a guarantee that data disappears at a particular moment.

For authentication, expiry should be part of a broader session policy. The server should be able to invalidate a session, and sensitive sessions may require expiration or reauthentication based on application needs.

What Secure, HttpOnly, and SameSite do

These attributes address different risks and are often used together.

Secure

Secure tells the browser to send the cookie only over secure connections, typically HTTPS. Use it for session cookies on sites served over HTTPS. It does not encrypt the cookie while it is stored in the browser, and it does not make an insecure page safe.

HttpOnly

HttpOnly prevents page scripts from reading the cookie through JavaScript APIs such as document.cookie. This can reduce the ability of injected script to steal a session cookie. The browser still sends the cookie with eligible requests, so HttpOnly does not prevent cross-site request forgery (CSRF), stop malicious scripts from performing actions as the user, or replace protection against cross-site scripting.

SameSite

SameSite controls whether a cookie is included in certain cross-site requests. Its common values are:

  • Strict: Restricts sending the cookie in cross-site contexts. This can provide stronger isolation, but may interrupt flows where a user follows an external link back to the site.
  • Lax: Allows the cookie in some cross-site navigations, while restricting many cross-site subrequests. It is a common choice for session cookies, but test the flows your application needs.
  • None: Allows cross-site use when browser policy permits it. It must be paired with Secure in modern browser behavior.

Browser defaults and privacy protections can affect cookie behavior. Set the attribute explicitly rather than relying on an assumed default. SameSite can help reduce CSRF exposure, but it is not a complete CSRF defense; use appropriate tokens or other application-specific protections for state-changing actions.

A useful hardening pattern for a host-wide session cookie is the __Host- prefix, when supported by the application environment. Such cookies require Secure, Path=/, and no Domain attribute. Check current browser documentation and test compatibility before relying on a prefix.

Cookies for session management

A common session design stores an opaque session identifier in a cookie and keeps session state on the server. On each request, the server validates the identifier and looks up the corresponding session. The cookie should not contain a password or other sensitive data simply because it is stored in the browser.

A secure implementation typically considers these steps:

  1. Generate session identifiers using a cryptographically secure random source.
  2. Send them only over HTTPS and set appropriate cookie attributes, such as Secure, HttpOnly, and a deliberate SameSite value.
  3. Rotate the session identifier after login or another privilege change to reduce session-fixation risk.
  4. Enforce expiration and invalidate sessions on the server when users log out or when policy requires revocation.
  5. Avoid logging full session-cookie values, and keep access to session data appropriately restricted.

The right lifetime and cross-site behavior depend on the application. For example, an identity flow that relies on cross-site requests may need a different SameSite configuration than a basic first-party site. Test those flows rather than weakening settings indiscriminately.

Cookies, local storage, and URL parameters

These mechanisms can all carry data, but they behave differently.

MechanismAutomatically sent with requests?Typical usesImportant considerations
CookiesYes, when the request matches the cookie's scope and browser rulesSessions, server-readable preferencesScope and security attributes matter; automatic sending can create CSRF considerations
localStorageNoClient-side preferences or application dataJavaScript-accessible; data persists until cleared or removed; do not store secrets that should be protected from script access
URL parametersIncluded in the URL when a request navigates to or fetches itFilters, pagination, shareable stateMay appear in browser history, logs, bookmarks, and referrer information; avoid putting secrets in them

Cookies are useful when the server needs a value on subsequent requests. Local storage is useful when client-side code needs persistent data that does not need to accompany every request. URL parameters are useful for state that should be addressable or shareable, not for confidential values.

Tracking uses and browser privacy

Cookies can support analytics and advertising by recognizing a browser over time. A first-party cookie is generally set in the context of the site the visitor is using. A third-party cookie is associated with a different site embedded or requested in that context, such as an external service. The distinction is based on browsing context and site relationships, not simply on whether the cookie was created by a company other than the site owner.

Third-party cookie availability is increasingly shaped by browser privacy features, user settings, and changes in browser policy. As a result, tracking systems cannot assume the same cookie behavior for every visitor. First-party cookies can also be used for measurement or tracking, so the label alone does not determine whether a practice is privacy-preserving.

For website owners, collect only the data needed for a clear purpose, set retention periods deliberately, and explain cookie use in line with applicable privacy requirements. Consent and disclosure obligations depend on jurisdiction and implementation; cookie attributes alone do not establish compliance.

Practical workflow for setting an application cookie

For a typical HTTPS application that uses a server-managed session:

  1. Decide whether the cookie needs to be host-only or shared with subdomains. Prefer host-only scope unless sharing is required.
  2. Choose a Path and lifetime based on the application. Avoid treating Path as access control.
  3. Set Secure and HttpOnly for sensitive session identifiers.
  4. Choose SameSite based on the application's navigation and integration needs. Add separate CSRF protections where appropriate.
  5. Keep the session value opaque, rotate it at privilege changes, and make server-side invalidation possible.
  6. Test in the browsers and flows your users rely on, including sign-in, sign-out, redirects, and any cross-site integrations.

A server response might look like this:

Set-Cookie: __Host-session=opaque-value; Path=/; Max-Age=1800; Secure; HttpOnly; SameSite=Lax

This is an illustrative header, not a complete session implementation. The server must still generate and validate the session identifier, manage expiry and revocation, and protect state-changing requests.

Common mistakes and troubleshooting

  • Expecting JavaScript to read an HttpOnly cookie: It is intentionally unavailable to document.cookie. Inspect the server response and request headers in developer tools instead.
  • Setting SameSite=None without Secure: Modern browsers generally reject this combination. Use it only when cross-site cookie behavior is actually needed and the site uses HTTPS.
  • Assuming a cookie is sent to every subdomain: A host-only cookie is not automatically shared with sibling subdomains. Review the Domain attribute and the request host.
  • Using Path as a security boundary: Path controls when a cookie is sent; it does not isolate code or applications sharing an origin.
  • Treating a session cookie as guaranteed temporary storage: Session restoration and browser policies can affect its lifetime. Use server-side expiration and revocation for session control.
  • Storing secrets in URLs or client-accessible storage: URLs can be exposed in more places than expected, while script-accessible storage can be read by scripts running in the origin. Choose storage based on the threat model.
  • Assuming SameSite alone prevents CSRF: It reduces some cross-site cookie sending, but applications should use suitable CSRF defenses and validate state-changing requests.

Conclusion

Cookies connect otherwise separate HTTP requests, making them useful for sessions and preferences—and potentially for tracking. Understanding scope, expiry, and the Secure, HttpOnly, and SameSite attributes helps developers choose safer defaults. Use cookies when browser-to-server request behavior is needed, and choose local storage or URL parameters only when their different exposure and persistence characteristics fit the job.

References