Codeskill

Learn to code, step by step

Browser storage (local, session, IndexedDB intro)

Browser storage – when to use localStorage, sessionStorage, cookies, and IndexedDB. You have fetched data from servers; sometimes you need to persist state on the client too.

localStorage and sessionStorage

Both store string key/value pairs. localStorage survives tab closes (same origin). sessionStorage clears when the tab ends. Capacity is roughly a few megabytes – not for large binaries.

const KEY = 'prefs:v1';

function loadPrefs() {
  try {
    return JSON.parse(localStorage.getItem(KEY)) ?? { theme: 'light' };
  } catch {
    return { theme: 'light' };
  }
}

function savePrefs(prefs) {
  localStorage.setItem(KEY, JSON.stringify(prefs));
}

Always JSON.stringify objects. Wrap parse in try/catch – users can edit storage in devtools and leave garbage behind.

Storage events

window.addEventListener('storage', (event) => {
  if (event.key === KEY && event.newValue) {
    applyPrefs(JSON.parse(event.newValue));
  }
});

The storage event fires in other tabs, not the one that wrote. Handy for syncing theme across tabs.

What not to store

  • Passwords, tokens, or payment details – use HttpOnly cookies from the server when auth is involved.
  • Large datasets – IndexedDB or the server.
  • Anything sensitive on shared computers – localStorage is plain text.

IndexedDB intro

IndexedDB is the browser’s structured store – objects, indexes, async API. Use it when you need offline caches, drafts, or more data than localStorage allows.

function openDb() {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open('notes-app', 1);
    req.onupgradeneeded = () => {
      const db = req.result;
      if (!db.objectStoreNames.contains('notes')) {
        db.createObjectStore('notes', { keyPath: 'id' });
      }
    };
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}

The API is verbose. Wrapper libraries (Dexie, idb) simplify daily use. For these tutorials, know IndexedDB exists and when to reach for it; deep offline apps are advanced territory.

Cookies in brief

Cookies ride along on HTTP requests – session ids, consent flags. Size limits are tight. Prefer localStorage for purely client UI prefs; let the server set HttpOnly cookies for auth.

Next: regular expressions for tasks you actually meet – validate, parse, replace.

PreviousForms and the constraint validation API