How do you store and retrieve JavaScript objects in HTML5 localStorage and sessionStorage? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you store and retrieve JavaScript objects in HTML5 localStorage and sessionStorage?

message-square
0

To store and retrieve JavaScript objects in HTML5 localStorage and sessionStorage, serialize the object to a JSON string using JSON.stringify(obj) when saving (setItem(key, jsonStr)), and parse it back into a JavaScript object using JSON.parse(rawStr) when reading (getItem(key)), wrapped in a try...catch block in case the stored string is corrupted or invalid JSON. Because Web Storage only stores strings natively, saving an object directly without JSON.stringify() coerces it to "[object Object]", and JSON.parse() also revives plain data rather than class instances or functions.


1. Saving and Reading Objects with JSON.stringify() and JSON.parse()

Both localStorage (persists across browser sessions/restarts) and sessionStorage (scoped to the current browser tab/session) share the same setItem, getItem, and removeItem methods:

// Save a JavaScript object as JSON into localStorage or sessionStorage
function saveStorageObject(storage, key, value) {
  if (typeof key !== "string" || key.trim().length === 0) {
    throw new TypeError("Expected storage key to be a non-empty string.");
  }

  const serialized = JSON.stringify(value);
  storage.setItem(key, serialized);
}

// Retrieve and safely parse a JSON object from storage, falling back on missing/invalid data
function readStorageObject(storage, key, fallbackValue = null) {
  if (typeof key !== "string" || key.length === 0) {
    return fallbackValue;
  }

  const raw = storage.getItem(key);
  if (raw === null) {
    return fallbackValue;
  }

  try {
    return JSON.parse(raw);
  } catch (err) {
    console.warn(`Failed to parse stored JSON for key "${key}":`, err);
    return fallbackValue;
  }
}

// Example usage:
const userPrefs = { theme: "dark", compactMode: true, favorites: ["js", "node"] };
saveStorageObject(window.localStorage, "user_prefs", userPrefs);

const restoredPrefs = readStorageObject(window.localStorage, "user_prefs", {});
console.log(restoredPrefs.theme); // "dark"
  • Always wrap JSON.parse() in try...catch: Manually edited or truncated storage entries throw a SyntaxError when parsed.
  • Check for null first: storage.getItem(key) returns null when no key exists; returning a clean fallbackValue avoids unnecessary parse errors.

2. Choosing Between localStorage and sessionStorage

Pick localStorage when state should survive page reloads and browser restarts on that origin, or sessionStorage when state belongs strictly to a single tab’s lifetime:

// Store temporary wizard state in sessionStorage vs. persistent settings in localStorage
const draftCheckout = { step: 2, promoCode: "SAVE10" };
saveStorageObject(window.sessionStorage, "checkout_draft", draftCheckout);

const activeDraft = readStorageObject(window.sessionStorage, "checkout_draft", { step: 1 });
console.log(activeDraft.step); // 2
  • Origin-scoped: Both storages are isolated by protocol, domain, and port (http://, https://, host, and port).
  • Tab isolation for sessionStorage: Duplicating a tab copies sessionStorage initially, after which each tab’s changes stay independent until the tab closes.

3. JSON Serialization Caveats and Quota/Privacy Guards

Because JSON.stringify() converts objects to plain JSON text, certain types or storage states require care:

// Guard against storage quota errors or private/restricted browsing contexts
function trySaveStorageObject(storage, key, value) {
  try {
    saveStorageObject(storage, key, value);
    return true;
  } catch (err) {
    // Handles QuotaExceededError or SecurityError in restricted contexts
    console.warn(`Could not write "${key}" to storage:`, err);
    return false;
  }
}

// Example usage:
const saved = trySaveStorageObject(window.sessionStorage, "temp_filter", { page: 1 });
console.log(saved); // true or false
  • Functions, undefined, and circular references: JSON.stringify() omits function properties and undefined object values, converts Date instances to ISO strings, and throws a TypeError on circular object references.
  • Avoid storing sensitive secrets: Web Storage is accessible to any JavaScript running on the page, so avoid storing sensitive tokens or credentials in localStorage or sessionStorage.

TL;DR: Store objects in localStorage or sessionStorage with storage.setItem(key, JSON.stringify(obj)) and read them back with JSON.parse(storage.getItem(key)) inside a try...catch block—returning a fallback when getItem() returns null or parsing fails.