๐Ÿ’พ Day 20 — LocalStorage & SessionStorage

๐Ÿ’พ Day 20 — LocalStorage & SessionStorage

Hey guys Today we’ll learn how to store data inside the browser: what to store, how to store, and when to use LocalStorage vs SessionStorage — plus patterns for building resilient client-side storage.


๐Ÿ”Ž What are LocalStorage & SessionStorage?

The Web Storage API provides two simple key/value stores: localStorage and sessionStorage. They are synchronous, string-only, and scoped to the origin (protocol + host + port). Use them to persist small pieces of data on the client without a server.

๐Ÿ“Œ Differences at a glance

  • localStorage — persists across browser sessions and survives closing the tab/window. Good for long-term preferences, offline drafts, and small caches.
  • sessionStorage — lasts only for the tab session. When the tab is closed, data is cleared. Useful for one-tab temporary state like a multi-step form in a single session.

⚙️ Getting started — Basic API

// set
localStorage.setItem('theme', 'dark');
sessionStorage.setItem('formStep', '2');

// get
const theme = localStorage.getItem('theme');

// remove
localStorage.removeItem('theme');

// clear
sessionStorage.clear();
  

๐Ÿงญ Storing objects (serialize/deserialize)

The storage APIs save strings only. To store objects or arrays, convert them to JSON with JSON.stringify and back with JSON.parse.

const user = { id: 1, name: "Rahul", prefs: { theme: "dark" } };
localStorage.setItem('user', JSON.stringify(user));

const stored = JSON.parse(localStorage.getItem('user') || '{}');
console.log(stored.name); // "Rahul"
  

๐Ÿ”’ Security & size considerations

  • Never store secrets: Do NOT store passwords, tokens, or PII in plain localStorage. It’s accessible by any script running on the page (XSS risk).
  • Size limits: Browsers typically allow ~5–10MB per origin. Use it for lightweight caching, not full data dumps.
  • Quotes & escaping: JSON.stringify handles escaping—avoid manual string building.

๐Ÿ“ˆ Common use cases

  1. Persist theme or UI preferences (dark/light, font-size).
  2. Cache API responses for quick UI rendering (with stale-while-revalidate).
  3. Save form drafts locally so users don’t lose work.
  4. Store feature flags or simple analytics markers.

๐Ÿงฉ Pattern: Namespaces & versioning

To avoid key collisions and make migration easier, use a namespace and include a version number:

const NS = "myapp:v1:";

function save(key, value) {
  localStorage.setItem(NS + key, JSON.stringify(value));
}

function load(key) {
  const raw = localStorage.getItem(NS + key);
  return raw ? JSON.parse(raw) : null;
}
  

๐Ÿงฐ Pattern: Storage wrapper with fallback

Build a small wrapper to handle unavailable storage (private mode) and to provide graceful fallback to in-memory storage.

function storageAvailable(type = 'localStorage') {
  try {
    const storage = window[type];
    const x = '__test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return false;
  }
}

const store = storageAvailable() ? localStorage : (function(){ let mem = {}; return { getItem:k=>mem[k]||null, setItem:(k,v)=>mem[k]=v, removeItem:k=>delete mem[k] } })();
  

๐Ÿš€ Practical example — Simple preferences

Save a theme preference and apply it on load.

// save
document.querySelector('#themeToggle').addEventListener('click', () => {
  const current = localStorage.getItem('theme') === 'dark' ? 'light' : 'dark';
  localStorage.setItem('theme', current);
  document.documentElement.setAttribute('data-theme', current);
});

// apply on load
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
  

๐Ÿงช Mini tasks (practice)

  1. Save user form progress in localStorage and restore it on reload.
  2. Implement a stale-while-revalidate cache for a list endpoint: show cached data immediately, then refresh in background.
  3. Build a toggle for compact/comfortable layout and persist the choice.

๐Ÿงพ When NOT to use localStorage

  • Don’t use it as a database for large datasets.
  • Don’t store authentication tokens unless you understand XSS risks—prefer httpOnly cookies or IndexedDB with proper controls.
  • Don’t use it for cross-origin data sharing; it’s origin-scoped.

✅ Summary

LocalStorage and SessionStorage are simple and useful for many client-side needs. Use JSON for objects, wrap the API for resilience, namespace keys, and avoid storing secrets. When you outgrow localStorage, consider IndexedDB or server-side persisting.

Comments