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.

JavaScript6 min readConcept 36 of 62

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

// 1. Save to the hard drive
localStorage.setItem("theme", "light");
// 2. Read on page load
const saved = localStorage.getItem("theme");
localhost:3000
☀️ Light Mode
DevTools: Local Storage
Key
Value
Empty
iWhen you click "Simulate Page Reload", the app's RAM is completely wiped. But because the theme was saved to localStorage (the hard drive), the app can instantly read it on boot and restore your exact state!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If you want to save a user's shopping cart so it is still there when they return to your website tomorrow, which should you use?
  2. 2How do you correctly save a JavaScript array in `localStorage`?
  3. 3Which storage mechanism is designed specifically to be sent back and forth between the browser and the server?

Remember this

  • localStorage persists data even after the browser is closed.
  • sessionStorage clears data when the tab is closed.
  • Web Storage can only store strings; use JSON.stringify for 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.