← All posts
7 min read

Cookies, Sessions, and Local Storage: How Websites Remember State

#technology#computer-science#cookies#web
📑 On this page

HTTP requests are independent messages. A server does not automatically know that two requests came from the same signed-in user or that a visitor selected dark mode yesterday.

Web applications add state through browser and server mechanisms.

Cookies are small browser-managed values associated with requests. Sessions commonly store user state on the server and use a cookie as an identifier. Web Storage keeps origin-scoped data in the browser.

Each mechanism has different security, lifetime, and communication behavior.

Cookies

A server can send:

Set-Cookie: session_id=abc123; Secure; HttpOnly; SameSite=Lax

The browser stores the cookie and sends it with later matching requests:

Cookie: session_id=abc123

Matching depends on:

  • Domain
  • Path
  • Expiry
  • Secure flag
  • SameSite policy

Cookies are small and included in requests, so storing large data in them wastes bandwidth.

Session identifiers

A common login design stores session data on the server.

The cookie contains an unpredictable identifier:

abc123 → user 42, authenticated, expires at ...

For each request:

  1. Browser sends the cookie.
  2. Server looks up the session.
  3. It verifies validity.
  4. It attaches user identity and authorization context.

Logging out invalidates or removes the server session and clears the browser cookie.

An attacker who steals a valid session identifier can impersonate the user until expiry or revocation.

HttpOnly and Secure

HttpOnly prevents ordinary page JavaScript from reading the cookie.

This reduces session theft through some XSS attacks, although malicious code can still make authenticated requests from the page.

Secure tells the browser to send the cookie only over HTTPS.

Neither flag validates server authorization. They protect transport and client exposure.

Authentication cookies should generally use both.

SameSite

Cookies can be sent when navigation or requests originate from another site.

The SameSite attribute controls cross-site behavior:

  • Strict: strongest restriction
  • Lax: allows selected top-level navigation behavior
  • None: permits cross-site use and requires Secure

SameSite helps reduce cross-site request forgery, or CSRF.

Applications requiring cross-site embedding or identity flows must choose deliberately.

CSRF

Suppose a user is logged into a bank. A malicious page causes the browser to submit a transfer request to the bank.

The browser might automatically include bank cookies.

The bank must distinguish legitimate user intent using:

  • SameSite cookies
  • CSRF tokens
  • Origin or Referer validation
  • Reauthentication for sensitive actions
  • Correct methods and API design

HTTPS does not prevent CSRF because the browser can securely send the attacker's induced request.

Local storage

localStorage stores string key-value pairs for an origin.

localStorage.setItem("theme", "dark");

It persists across browser restarts until cleared.

It is not automatically sent with HTTP requests.

Page JavaScript in the origin can read it, so it is exposed if the site has XSS.

Good uses include non-sensitive preferences and small client state.

Session storage

sessionStorage has a similar string key-value interface but is scoped to a browser tab's page session.

It generally disappears when the tab closes.

It can store transient workflow state that should not be shared across tabs.

The word session here refers to browser-tab lifetime, which differs from a server authentication session.

IndexedDB

For larger structured browser data, IndexedDB provides an asynchronous database.

It supports:

  • Objects and indexes
  • Transactions
  • Significant storage
  • Offline application data

Progressive web applications can combine IndexedDB with service workers and caches for offline operation.

Browser quota, eviction, version migration, and privacy policy still apply.

A concrete login flow

  1. User submits credentials over HTTPS.
  2. Server verifies them.
  3. Server creates a random session record.
  4. Response sets an HttpOnly, Secure, SameSite cookie.
  5. Browser stores the cookie.
  6. Later requests include it automatically.
  7. Server looks up the session and checks authorization.
  8. On logout, server invalidates the session.

The cookie should not contain the password.

Session identifiers need sufficient randomness and should rotate after login to prevent session fixation.

Signed tokens

Some applications store signed tokens in cookies.

The server can verify claims without a central session lookup.

Trade-offs include:

  • Harder immediate revocation
  • Token size
  • Claim staleness
  • Key rotation
  • Replay risk

"Stateless authentication" still depends on server keys, user records, authorization policy, and often revocation or refresh state.

The storage location and token format do not solve authorization automatically.

Cookie Domain and Path influence where it is sent.

A host-only cookie is limited to the exact host that set it.

A broadly scoped domain cookie can reach multiple subdomains, increasing exposure if one subdomain is less trusted.

Use the narrowest scope that supports the application.

Cookie prefixes such as __Host- and __Secure- enforce stronger browser rules when used correctly.

Expiry

A session cookie normally lasts for the browser session.

A persistent cookie has Expires or Max-Age.

Server sessions need their own expiry regardless of the browser cookie. A copied cookie should not remain valid forever merely because one client retained it.

Useful policies include:

  • Idle timeout
  • Absolute lifetime
  • Refresh rotation
  • Device/session management
  • Revocation after password change

Security and user convenience trade against each other.

Privacy and tracking

Third-party cookies historically enabled cross-site tracking.

Browsers increasingly block or partition third-party state.

Sites also use:

  • First-party identifiers
  • Link decoration
  • Fingerprinting
  • Server-side tracking

Cookie banners do not themselves provide privacy. Actual collection, purpose, retention, sharing, consent, and legal compliance determine the practice.

Clearing site data

Clearing cookies can log users out because session identifiers disappear.

Clearing all site data can also remove:

  • Local storage
  • IndexedDB
  • Cache
  • Service workers

Cloud and server data remains unless separately deleted.

Private browsing isolates or discards much local state but does not erase server-side account records.

Common misunderstandings

"Cookies are programs"

They are small data values managed by the browser. Their use can affect behavior and tracking, but they are not executable code.

Often the cookie contains only an identifier while session data lives server-side.

"Local storage is automatically sent to the server"

No. JavaScript must read and send it deliberately.

"Deleting cookies deletes the online account"

It removes local identifiers and preferences; server account data remains.

Knowledge check

1. Why is HttpOnly useful for a session cookie?

It prevents ordinary page JavaScript from reading the cookie, reducing some session-token theft through XSS.

2. What is the difference between localStorage and cookies?

Local storage is read by origin JavaScript and not automatically sent; matching cookies are automatically attached to requests.

3. Why can CSRF work even with HTTPS?

The browser can securely send an unwanted cross-site-triggered request along with authentication cookies.

4. What happens to server account data when cookies are cleared?

It remains on the server unless the user or service separately deletes it.

The one idea to remember

Web state is divided among browser-managed cookies, server-side sessions or tokens, and origin storage.

Choose storage based on whether data must travel with requests, who may read it, how long it should live, and what happens under XSS, CSRF, theft, and logout.

Next, the series moves from using web applications to understanding programs themselves, beginning with what a program is.