JavaScript Web Storage API

The Web Storage API provides mechanisms for storing key-value pairs in the browser. It offers two storage objects: localStorage (persists across sessions) and sessionStorage (cleared when the tab is closed).

localStorage vs sessionStorage

Both localStorage and sessionStorage provide the same API, but they differ in persistence and scope.

FeaturelocalStoragesessionStorage
PersistenceUntil manually clearedUntil tab/window closes
ScopeShared across all tabs (same origin)Per tab/window only
Storage limit~5-10 MB~5-10 MB
Survives browser restartYesNo
Use caseUser preferences, themesTemporary form data
localStorage vs sessionStorage
// localStorage persists across browser sessions
// sessionStorage is cleared when the tab closes

// Both use the same API:
console.log('localStorage type: ' + typeof localStorage);
console.log('sessionStorage type: ' + typeof sessionStorage);

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

console.log('localStorage available: ' + storageAvailable('localStorage'));
console.log('sessionStorage available: ' + storageAvailable('sessionStorage'));

setItem, getItem, removeItem, clear

The Storage API provides four main methods: setItem() to store data, getItem() to retrieve data, removeItem() to delete a specific item, and clear() to remove all items.

Basic Storage Methods
// setItem(key, value) - stores a value
localStorage.setItem('username', 'Alice');
localStorage.setItem('theme', 'dark');
localStorage.setItem('fontSize', '16');

// getItem(key) - retrieves a value
const user = localStorage.getItem('username');
console.log('Username: ' + user);

// Non-existent key returns null
const missing = localStorage.getItem('nonexistent');
console.log('Missing: ' + missing);

// removeItem(key) - removes one item
localStorage.removeItem('fontSize');
console.log('After remove: ' + localStorage.getItem('fontSize'));

// clear() - removes all items
localStorage.clear();
console.log('After clear: ' + localStorage.getItem('username'));

Storing Objects with JSON

Web Storage only stores strings. To store objects or arrays, you must convert them to JSON strings using JSON.stringify() and parse them back with JSON.parse().

Storing Objects as JSON
// Storing an object
const settings = {
  theme: 'dark',
  language: 'en',
  notifications: true
};

localStorage.setItem('settings', JSON.stringify(settings));

// Retrieving and parsing the object
const stored = localStorage.getItem('settings');
const parsed = JSON.parse(stored);
console.log('Theme: ' + parsed.theme);
console.log('Language: ' + parsed.language);
console.log('Notifications: ' + parsed.notifications);

// Storing an array
const cart = ['item1', 'item2', 'item3'];
localStorage.setItem('cart', JSON.stringify(cart));
const savedCart = JSON.parse(localStorage.getItem('cart'));
console.log('Cart: ' + savedCart);

localStorage.clear();

Storage Events

The storage event fires on other tabs/windows when localStorage is modified. This enables communication between browser tabs of the same origin.

Listening for Storage Events
// The storage event fires on OTHER windows/tabs
// when localStorage is modified

// window.addEventListener('storage', function(event) {
//   console.log('Key changed: ' + event.key);
//   console.log('Old value: ' + event.oldValue);
//   console.log('New value: ' + event.newValue);
//   console.log('URL: ' + event.url);
// });

// Simulating what the event object looks like
const storageEvent = {
  key: 'theme',
  oldValue: 'light',
  newValue: 'dark',
  url: 'https://example.com',
  storageArea: 'localStorage'
};

console.log('Key: ' + storageEvent.key);
console.log('Changed from: ' + storageEvent.oldValue);
console.log('Changed to: ' + storageEvent.newValue);
console.log('Origin: ' + storageEvent.url);

Storage Limits and Use Cases

Web Storage has size limits (typically 5-10 MB per origin). It is suitable for storing small amounts of non-sensitive data. For larger data, consider IndexedDB.

Practical Use Cases
// Use case 1: Remember user preferences
function savePreference(key, value) {
  localStorage.setItem('pref_' + key, JSON.stringify(value));
}

function getPreference(key, defaultValue) {
  const stored = localStorage.getItem('pref_' + key);
  return stored ? JSON.parse(stored) : defaultValue;
}

savePreference('darkMode', true);
savePreference('fontSize', 18);

console.log('Dark mode: ' + getPreference('darkMode', false));
console.log('Font size: ' + getPreference('fontSize', 14));
console.log('Missing pref: ' + getPreference('color', 'blue'));

localStorage.clear();
📝 Note: Never store sensitive data (passwords, tokens, personal info) in Web Storage. It is accessible to any JavaScript running on the page, making it vulnerable to XSS attacks. Use HttpOnly cookies for authentication tokens instead.
Exercise:
What happens to sessionStorage data when the browser tab is closed?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.