Difference between cookie, sessionStorage, and localStorage

Cookie, sessionStorage, and localStorage are all methods used to store data on the client side, but they have different characteristics and use cases:

Cookies

  • Capacity: 4KB
  • Accessibility: All windows
  • Expiration: Manually set
  • Passed in HTTP request: Yes
  • Storage: Browser and Server
  • Use cases: session management, personalization, tracking, and analytics

Session Storage

  • Capacity: 5MB
  • Accessibility: Private for tab
  • Expiration: On tab close
  • Passed in HTTP request: No
  • Storage: Only browser
  • Use cases: similar to localStorage with a limitation of data expiration on tab close

LocalStorage

  • Capacity: 5/10 MB, depending on the browser
  • Accessibility: All windows
  • Expiration: Never
  • Passed in HTTP request: No
  • Storage: Browser only
  • Use cases: save user preferences and settings, cache date to reduce server requests, shopping cart state

Summary

  • Cookie is a small text file that is stored on the user's computer by the web browser. It is used to store information about the user and their preferences.
  • sessionStorage is a storage for a single tab in a browser. It is used to store data that is only available for the current tab.
  • localStorage is a storage for a browser. It is used to store data that is available for all tabs and windows.
Feature Cookie sessionStorage localStorage
Capacity 4KB 5MB 5-10MB (browser dependent)
Accessibility All windows Private for tab All windows
Expiration Manually set On tab close Never
Passed in HTTP request Yes No No
Storage Location Browser and Server Browser only Browser only
Use Cases Session management, personalization, tracking, analytics Temporary data for single tab, form data during navigation User preferences, settings, cache data, shopping cart state