Skip to content

Web Storage API

This lesson explains Web Storage API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Web Storage API Overview

The HTML5 Web Storage API provides a simple way to store key-value data directly in the browser. It replaces many older cookie-based storage patterns with a larger, faster, and easier-to-use client-side storage model that does not send data to the server on every request.

Web Storage includes two main interfaces: localStorage for persistent data and sessionStorage for tab-scoped data. Both store string values and are commonly used for user preferences, themes, draft forms, shopping carts, and lightweight application state.

Feature Description
API Name Web Storage API
Main Objects localStorage and sessionStorage
Storage Type Key-value string storage in the browser
Data Format Strings only
Typical Limit Approximately 5-10 MB per origin
Common Uses Preferences, themes, drafts, carts, client-side state

Basic Web Storage Example

// Save a value

localStorage.setItem(
  "username",
  "Alex"
);

// Read a value

const username =
  localStorage.getItem("username");

console.log(username);

// Remove a value

localStorage.removeItem("username");

// Clear all local storage

localStorage.clear();

Web Storage uses a simple key-value model. Values persist in localStorage until they are removed, while sessionStorage lasts only for the current browser tab session.

How Web Storage Works

Both storage types are accessed through the same method names, but they differ in scope and lifetime. Data is stored per origin, which means each domain has its own isolated storage area.

Step Description Example Syntax
Choose Storage Pick persistent or session-based storage. localStorage or sessionStorage
Save Data Store a string value using a key. localStorage.setItem("key", "value")
Read Data Retrieve a stored value by key. localStorage.getItem("key")
Update Data Overwrite an existing key with a new value. localStorage.setItem("key", "new value")
Remove Data Delete one key or clear all stored values. removeItem() or clear()
React to Changes Listen for storage updates across tabs. window.addEventListener("storage", callback)

localStorage vs sessionStorage

Feature localStorage sessionStorage
Lifetime Persists after browser restart. Cleared when the tab or window closes.
Scope Shared across tabs from the same origin. Isolated to the current tab session.
Best For Themes, language, saved preferences. Temporary form drafts and wizard state.
Storage Event Fires in other tabs when data changes. Usually limited to the current tab context.
API Methods setItem(), getItem(), removeItem() Same methods as localStorage

Session Storage Example

// Save temporary wizard step

sessionStorage.setItem(
  "checkoutStep",
  "shipping"
);

// Read current step

const step =
  sessionStorage.getItem("checkoutStep");

console.log(step);

// Remove when checkout completes

sessionStorage.removeItem("checkoutStep");

Use sessionStorage when data should survive page reloads but should not remain after the user closes the tab, such as multi-step forms or temporary navigation state.

Store Objects with JSON

const user = {
  id: 1,
  name: "Alex",
  theme: "dark"
};

// Save object as JSON string

localStorage.setItem(
  "user",
  JSON.stringify(user)
);

// Read and parse object

const savedUser =
  JSON.parse(
    localStorage.getItem("user")
  );

console.log(savedUser.theme);

Web Storage only stores strings. To save objects, arrays, or numbers, serialize them with JSON.stringify() and parse them back with JSON.parse().

Loop Through Stored Keys

localStorage.setItem("theme", "dark");
localStorage.setItem("language", "en");
localStorage.setItem("cartCount", "3");

for (let i = 0; i < localStorage.length; i += 1) {
  const key =
    localStorage.key(i);

  const value =
    localStorage.getItem(key);

  console.log(key, value);
}

The length property and key() method let you inspect all stored entries. This is useful for debugging, migration scripts, and admin tools.

Listen for Storage Changes

window.addEventListener("storage", (event) => {
  console.log("Key changed:", event.key);
  console.log("Old value:", event.oldValue);
  console.log("New value:", event.newValue);
  console.log("Storage area:", event.storageArea);
});

// This event fires in other tabs,
// not in the tab that made the change

The storage event helps synchronize state across tabs. For example, if a user changes the theme in one tab, another open tab can update its UI automatically.

Safe Storage Helper

function saveToStorage(key, value) {
  try {
    localStorage.setItem(
      key,
      JSON.stringify(value)
    );
  } catch (error) {
    console.error("Storage failed:", error.message);
  }
}

function readFromStorage(key, fallback = null) {
  try {
    const value =
      localStorage.getItem(key);

    return value
      ? JSON.parse(value)
      : fallback;
  } catch (error) {
    console.error("Read failed:", error.message);
    return fallback;
  }
}

saveToStorage("settings", {
  theme: "dark",
  fontSize: 16
});

const settings =
  readFromStorage("settings", {
    theme: "light",
    fontSize: 14
  });

Wrap storage access in helper functions so you can handle quota errors, private browsing restrictions, and invalid JSON safely in production applications.

Feature Detection

function supportsWebStorage() {
  try {
    const testKey = "__storage_test__";
    localStorage.setItem(testKey, "1");
    localStorage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
}

if (supportsWebStorage()) {
  console.log("Web Storage is supported.");
} else {
  console.log("Web Storage is not available.");
}

Feature detection is important because storage may be disabled in private browsing modes, blocked by browser policy, or unavailable in older environments.

Common Web Storage Methods

Method / Property Description Common Use
setItem() Stores a key-value pair. Save preferences or app state.
getItem() Reads a value by key. Load saved settings.
removeItem() Deletes one stored key. Clear a single setting.
clear() Removes all keys in that storage area. Reset app data.
key() Returns the key at a given index. Iterate through stored entries.
length Returns the number of stored items. Count or audit stored data.

Common Web Storage Use Cases

  • Saving theme, language, and accessibility preferences.
  • Storing shopping cart items and recently viewed products.
  • Keeping draft form data before submission.
  • Remembering UI state such as sidebar collapse or tab selection.
  • Caching lightweight client-side configuration or feature flags.
  • Preserving temporary wizard or checkout progress in a tab.

Web Storage Best Practices

  • Choose localStorage for persistent data and sessionStorage for temporary tab data.
  • Store only strings, and use JSON for objects and arrays.
  • Never store passwords, tokens, or other sensitive secrets in Web Storage.
  • Use clear, consistent key names such as app:theme or user:settings.
  • Wrap storage access in try/catch blocks to handle quota and privacy-mode errors.
  • Remove unused keys instead of letting stale data accumulate.
  • Use the storage event to sync UI state across tabs when needed.

Security Considerations

  • Web Storage is accessible to JavaScript on the same origin, so XSS can expose stored data.
  • Do not use Web Storage as a secure place for authentication credentials.
  • Validate and sanitize any data read back from storage before using it in the DOM.
  • Prefer HttpOnly cookies for session tokens when server-side security is required.
  • Consider IndexedDB or server storage for larger or more structured datasets.

Common Web Storage Mistakes

  • Storing objects directly without JSON.stringify().
  • Assuming getItem() returns an object instead of a string or null.
  • Using localStorage when sessionStorage would be safer for temporary data.
  • Not handling QuotaExceededError when storage is full.
  • Storing large amounts of data and hurting performance.
  • Expecting the storage event to fire in the same tab that made the change.
  • Saving sensitive user data without considering XSS risk.

Web Storage vs Cookies

Feature Web Storage Cookies
Storage Size About 5-10 MB per origin. About 4 KB per cookie.
Sent to Server No, stays in the browser. Yes, with HTTP requests.
Expiration Persistent or session-based by API choice. Configurable with expiry dates.
Best For Client-side preferences and UI state. Authentication and server-aware sessions.

Key Takeaways

  • The Web Storage API provides localStorage and sessionStorage for browser key-value storage.
  • Use setItem(), getItem(), and removeItem() to manage stored values.
  • Only strings can be stored directly, so serialize objects with JSON.
  • localStorage persists across sessions, while sessionStorage is tab-scoped.
  • Feature detection, safe helpers, and security awareness are important in production apps.

Pro Tip

Start with a small storage helper that handles JSON parsing, default values, and errors in one place. This keeps your app code clean and makes it easier to swap storage strategies later.