Advanced20 min read

Web Storage API

Store data in the browser using localStorage and sessionStorage for persistent client-side data.

localStorage vs sessionStorage

The Web Storage API provides two mechanisms for storing key-value pairs in the browser: localStorage and sessionStorage.

localStorage:

  • Data persists indefinitely — survives browser close and restart
  • Cleared only when explicitly removed by code or the user
  • Shared across all tabs/windows of the same origin

sessionStorage:

  • Data cleared when the tab is closed
  • Each tab has its own separate sessionStorage
  • Not shared between tabs

Shared characteristics:

  • Both store key-value pairs where both key and value are strings
  • ~5MB storage limit per origin
  • Subject to same-origin policy (only accessible from the same domain)
  • Synchronous API (blocks the main thread — avoid storing large amounts of data)
javascript
// localStorage persists
localStorage.setItem('theme', 'dark');
// Close browser, reopen — value is still there!

// sessionStorage is temporary
sessionStorage.setItem('tempData', 'gone when tab closes');

Basic Operations

Both localStorage and sessionStorage share the same API.

Setting values:

javascript
localStorage.setItem('username', 'Alice');
localStorage.setItem('score', '100');

Getting values:

javascript
const name = localStorage.getItem('username'); // 'Alice'
const missing = localStorage.getItem('nonexistent'); // null

Removing values:

javascript
localStorage.removeItem('username');

Clearing everything:

javascript
localStorage.clear(); // removes ALL items

Other properties:

javascript
// Number of stored items
console.log(localStorage.length);

// Get key by index
console.log(localStorage.key(0)); // first key name

Important: All values are stored as strings. If you store a number, it comes back as a string:

javascript
localStorage.setItem('count', 42);
const count = localStorage.getItem('count');
console.log(typeof count); // 'string'
console.log(count);        // '42' (not 42)

Storing Complex Data

Since Storage only accepts strings, you must serialize objects and arrays with JSON.stringify() before storing, and parse them back with JSON.parse() when retrieving.

javascript
// Storing an object
const user = { name: 'Alice', age: 30, scores: [95, 87, 92] };
localStorage.setItem('user', JSON.stringify(user));

// Retrieving and parsing
const stored = localStorage.getItem('user');
const parsed = JSON.parse(stored);
console.log(parsed.name);    // 'Alice'
console.log(parsed.scores);  // [95, 87, 92]

Always handle nullgetItem returns null if the key does not exist, and JSON.parse(null) returns null (it does not throw):

javascript
const data = localStorage.getItem('maybeExists');
const result = data ? JSON.parse(data) : defaultValue;

Convenience wrapper functions:

javascript
function saveJSON(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function loadJSON(key, fallback = null) {
  const data = localStorage.getItem(key);
  return data ? JSON.parse(data) : fallback;
}

// Usage
saveJSON('settings', { theme: 'dark', lang: 'en' });
const settings = loadJSON('settings', { theme: 'light' });

Use Cases & Limitations

Good use cases for Web Storage:

  • User preferences — theme, language, font size
  • Form data drafts — auto-save form input so users do not lose work
  • Shopping cart — persist cart items between page refreshes
  • UI state — sidebar collapsed, last viewed tab, sort order
  • Simple caching — store API responses to reduce network requests

Limitations:

  • Strings only — must serialize/deserialize objects
  • Synchronous — can block the UI if overused
  • Limited size — ~5MB per origin
  • No expiration — localStorage has no built-in TTL (time-to-live)
  • No server access — data is only available client-side
  • No structured queries — can only get/set by key

Alternatives for more advanced needs:

  • Cookies — sent with every HTTP request, can set expiration, smaller (4KB)
  • IndexedDB — asynchronous, supports large amounts of structured data, transactions
  • Cache API — designed for caching network requests (used with Service Workers)

Security note: Never store sensitive data (passwords, tokens, personal information) in localStorage. It is accessible to any JavaScript on the page and vulnerable to XSS attacks.

Web Storage in Action

html
<div id="output"></div>

<script>
  // Store simple values
  localStorage.setItem('appName', 'Kodojo');
  localStorage.setItem('version', '1.0');

  // Store complex data with JSON
  const preferences = {
    theme: 'dark',
    fontSize: 16,
    notifications: true
  };
  localStorage.setItem('prefs', JSON.stringify(preferences));

  // Retrieve and parse
  const appName = localStorage.getItem('appName');
  const prefs = JSON.parse(localStorage.getItem('prefs'));

  // Handle missing data with fallback
  const language = localStorage.getItem('lang') || 'en';

  const output = document.getElementById('output');
  output.innerHTML = `
    <p>App: ${appName} v${localStorage.getItem('version')}</p>
    <p>Theme: ${prefs.theme}</p>
    <p>Font size: ${prefs.fontSize}px</p>
    <p>Language: ${language} (default)</p>
    <p>Items stored: ${localStorage.length}</p>
  `;

  // Clean up demo data
  localStorage.removeItem('appName');
  localStorage.removeItem('version');
  localStorage.removeItem('prefs');
</script>

What happens when you store an object directly in localStorage?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.