Tell me about cookies, sessionStorage, localStorage, IndexedDB
sobes.tech AI
Answer from AI
Cookies — small data sent by the server to the browser, which the browser stores and sends back on subsequent requests to the same domain. Used for authentication, session tracking, and storing user settings. They have size limitations (~4KB) and can be configured with security flags (HttpOnly, Secure).
sessionStorage — a web storage object available in the browser that stores data within a single tab session. Data is deleted when the tab or window is closed. Used for temporary storage of data that should not persist between sessions.
localStorage — also a web storage object, but data is stored permanently until explicitly deleted by the program or user. Allows storing up to several megabytes of data in the browser. Used for storing settings, cache, and other information that needs to persist between sessions.
IndexedDB — a more complex and powerful database in the browser that allows storing structured data (objects, files) as key-value pairs. Supports transactions, indexes, and queries. Used for offline applications and storing large volumes of data.
Example of using localStorage:
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');