Sobes.tech
Junior — Middle

What are the differences between data storage mechanisms in LocalStorage, SessionStorage, and cookies in the browser?

sobes.tech AI

Answer from AI

LocalStorage, SessionStorage, and cookies are three mechanisms for storing data in the browser, differing in volume, lifetime, and accessibility.

  • LocalStorage

    • Stores data without an expiration date (until manually deleted).
    • Usually around 5-10 MB in size.
    • Data is accessible across all tabs and windows of the same domain.
    • Not sent to the server with HTTP requests.
  • SessionStorage

    • Data lives only within a single session (while the tab is open).
    • Size similar to LocalStorage.
    • Data is accessible only in the current tab/window.
    • Not sent to the server.
  • Cookies

    • Can have an expiration date after which they are deleted.
    • Size is limited (about 4 KB per cookie).
    • Data is automatically sent to the server with each request to the relevant domain.
    • Used for authentication, tracking, etc.

Example of using LocalStorage:

localStorage.setItem('user', 'Alice');
const user = localStorage.getItem('user');