Sobes.tech
Junior

What methods of data storage in the browser are you aware of?

sobes.tech AI

Answer from AI

  • LocalStorage: Allows storing data without an expiration date. Available only for the current domain (Origin). Capacity up to 5-10 MB.
  • SessionStorage: Similar to LocalStorage, but data is stored only until the tab or browser window is closed. Capacity up to 5-10 MB.
  • IndexedDB: A high-performance NoSQL database built into the browser. Suitable for storing large volumes of structured data. Works asynchronously. Capacity up to hundreds of MB or even GB (depends on the browser and available space).
  • Cookies: Small pieces of data sent by the server and stored in the browser. Mainly used for authentication and session tracking. Automatically sent with each request to the server. Capacity up to 4 KB per cookie, no more than 20-50 cookies per domain.
  • Cache API: Part of Service Worker, used for caching requests and responses, enabling offline work and faster loading.

Comparison table:

Method Data capacity Storage duration Server access Data type Access
LocalStorage 5-10 MB Indefinite (until manually cleared) No Strings Client-side JS
SessionStorage 5-10 MB Until session ends No Strings Client-side JS
IndexedDB MBs to GBs Indefinite (until manually cleared) No Structured data Client-side JS
Cookies 4 KB per cookie Set by server Yes Strings JS and HTTP headers
Cache API Hundreds of MBs to GBs Until manually cleared Indirectly HTTP requests/responses JS (Service Worker)

Example of using LocalStorage:

// Saving data
localStorage.setItem('userName', 'John Doe');

// Reading data
const userName = localStorage.getItem('userName');
console.log(userName); // Output: John Doe

// Removing data
// localStorage.removeItem('userName');
// localStorage.clear(); // Remove all data

Example of using SessionStorage:

// Saving data
sessionStorage.setItem('cartId', 'abc123def456');

// Reading data
const cartId = sessionStorage.getItem('cartId');
console.log(cartId); // Output: abc123def456

// Removing data
// sessionStorage.removeItem('cartId');
// sessionStorage.clear(); // Remove all data

Example of setting cookies via JS (usually set by server for simplicity):

// Setting a cookie
document.cookie = "myCookie=myValue; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

// Reading all cookies
console.log(document.cookie);

IndexedDB and Cache API require more complex code and are usually used for advanced scenarios, so their implementation goes beyond a brief answer.