Web Storage: localStorage, cookies & IndexedDB
Learn how to save data directly inside the user's browser. Compare the persistence, capacity, and use-cases of localStorage, sessionStorage, Cookies, and IndexedDB.
Client-Side Databases
Historically, the only way to remember a user across page reloads was by storing data on a remote server.
Modern browsers now feature built-in storage systems, allowing your JavaScript to save user preferences, shopping carts, or even entire offline applications directly on their device.
The Four Storage Types
1. localStorage: Survives closing the browser. Stores about 5MB. Synchronous.
2. sessionStorage: Survives page reloads, but dies when the tab is closed. Stores about 5MB. Synchronous.
3. Cookies: Tiny (4KB) and sent to the server with *every* HTTP request. Used for authentication.
4. IndexedDB: A massive, asynchronous NoSQL database that can store hundreds of megabytes of complex objects.
Setting and Getting
The Web Storage API (localStorage and sessionStorage) is extremely simple. It acts like a giant dictionary.
localStorage.setItem('theme', 'dark') saves a value.
const theme = localStorage.getItem('theme') reads it back.
Persistence in Action
Change the theme preference and watch it save to localStorage. Then, simulate a page reload to see how the browser instantly remembers your choice!
Persistence Simulator
localStorage.setItem("theme", "light");
const saved = localStorage.getItem("theme");
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
localStoragepersists data even after the browser is closed.sessionStorageclears data when the tab is closed.- Web Storage can only store strings; use
JSON.stringifyfor objects. - Cookies are tiny (4KB) and sent to the server automatically.
- IndexedDB is an asynchronous database for massive amounts of data.
Done with this concept?
Mark it complete to track your progress. No login needed.