Web & Network6 min readLast updated: Thu Mar 14 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

Cookies vs LocalStorage vs SessionStorage

Modern browsers give developers several places to save data.

Cookies

Cookies are the oldest method. They are unique because they are automatically sent to the server with every HTTP request.

  • Size: Small (4KB).
  • Use Case: Authentication Tokens (Session IDs). The server needs to know who you are on every click.
  • Security: Can be marked HttpOnly so JavaScript cannot read them (prevents XSS attacks).

LocalStorage

LocalStorage is a key-value store in the browser.

  • Size: Large (5MB+).
  • Persistence: Data stays forever until deleted.
  • Network: Data is not sent to the server.
  • Use Case: User preferences (Dark Mode setting), Shopping Cart data (before login).

SessionStorage

Exactly like LocalStorage, but the data is deleted when the tab is closed.

  • Use Case: Form data (if you accidentally refresh the page, the data is saved, but you don't want it there next week).

Security Warning

Never store sensitive data (like passwords or credit cards) in LocalStorage. Any malicious script running on your page can read LocalStorage.