Sobes.tech
Middle+

What are localStorage, sessionStorage, and cookies? How do they differ from each other?

sobes.tech AI

Answer from AI

localStorage, sessionStorage and cookies are mechanisms for storing data on the client side in the browser, but they differ in size, lifetime, and data transfer method.

  • localStorage stores data without an expiration date until the user clears it manually. Data is only accessible on the same domain. The size is usually around 5-10 MB. It is not sent to the server with each request.

  • sessionStorage is similar to localStorage, but data only persists within a single browser session (as long as the tab is open). After closing the tab, data is deleted. It is also limited in size and only accessible on the same domain.

  • cookies are small data (up to 4 KB) that are automatically sent to the server with each HTTP request to the corresponding domain. You can set a lifespan, scope (domain, path), security flags (HttpOnly, Secure). They are used for authentication, session tracking.

Key differences:

  • Size: cookies < localStorage/sessionStorage
  • Lifetime: cookies — configurable, localStorage — permanent, sessionStorage — until the tab is closed
  • Server transfer: cookies are sent automatically, localStorage and sessionStorage are not

Example of using localStorage:

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
What are localStorage, sessionStorage, and cookies… - sobes.tech