2024-07-28
#browser
#storage
#cookies
#frontend
#security

Browser Storage & Sessions

Deep dive into Client-side storage: Cookies, LocalStorage, SessionStorage, and Server-side Sessions.

Cookies vs Sessions

Cookies

Small pieces of data (max 4KB) stored in the browser and sent with every HTTP request to the domain.

  • Server-Side Creation: Sent via Set-Cookie header.
  • Use Cases: Authentication tokens, Language preference, Tracking IDs.

Security Flags:

  • HttpOnly: Cannot be accessed via JavaScript (document.cookie). Prevents XSS attacks stealing tokens.
  • Secure: Only sent over HTTPS.
  • SameSite: Prevents CSRF attacks (Strict or Lax).

Sessions

Server-side storage of user state.

  1. User logs in.
  2. Server creates a Session (in memory/database) and generates a Session ID.
  3. Server sends Session ID to client (usually in a Cookie).
  4. Client sends Session ID with future requests.
  5. Server looks up data using the ID.

Difference:

  • Cookie: Data stored on Client (sent to server).
  • Session: Data stored on Server (referenced by Client).

Client-Side Storage Comparison

FeatureCookieLocal StorageSession Storage
Capacity4KB5-10MB5MB
LifespanManual (TTL)Permanent (until deleted)Tab closed
ScopeSent to ServerClient OnlyClient Only
AccessibilityAny windowAny windowSame tab
Use CaseAuth TokensApp Settings, CacheForm Data

Local Storage

  • Persistent key-value store.
  • NOT sent to the server automatically.
  • Synchronous (blocking) API.
  • Good for: Theme preference, unsaved drafts, shopping cart (for guests).

Session Storage

  • Similar to Local Storage, but cleared when the tab is closed.
  • Good for: Multi-step form progress, sensitive temporary data.

Connected Thoughts

Egor Zdioruc | Lead Full Stack Developer | Laravel & AI Solutions