乐闻世界logo
搜索文章和话题

What is the difference between Cookie and LocalStorage? Which storage method to use in which scenarios?

3月6日 21:41

Cookie and LocalStorage are both client-side storage mechanisms provided by browsers, but they have important differences in capacity, scope, API, and use cases.

Capacity limits

  • Cookie: about 4KB per Cookie, about 50-100 per domain
  • LocalStorage: about 5-10MB per domain

Data transmission

  • Cookie: automatically sent to the server with every HTTP request
  • LocalStorage: not automatically sent, needs to be manually read via JavaScript

API operations

  • Cookie: operated through document.cookie string, requires manual parsing
  • LocalStorage: provides simple key-value API (setItem, getItem, removeItem)

Expiration time

  • Cookie: can set expiration time or session-level
  • LocalStorage: permanent storage unless manually deleted or browser data is cleared

Scope

  • Cookie: can precisely control scope through Domain and Path attributes
  • LocalStorage: same-origin policy, only shared under same domain, protocol, and port

Security

  • Cookie: can set HttpOnly to prevent JavaScript access
  • LocalStorage: fully accessible by JavaScript, not suitable for storing sensitive information

Use case comparison

  • Cookie: session management, CSRF protection, data needed by server
  • LocalStorage: user preferences, cached data, offline application data

Code examples

javascript
// Cookie operations document.cookie = "name=value; expires=...; path=/"; // LocalStorage operations localStorage.setItem('key', 'value'); const value = localStorage.getItem('key');

Selection recommendations

  • Use Cookie for data that needs to be sent to the server
  • Use LocalStorage for pure client-side data
  • Use Cookie + HttpOnly for sensitive information
  • Use LocalStorage for large amounts of data
标签:Cookie