DEV3 Technologies home

DEV3 Developer Forum

How do I store objects and arrays in localStorage correctly?

JavaScript helpSolved0 views
dev3 ·

I saved an object to localStorage and reading it back gives '[object Object]'. How do I store structured data, and what are the limits and security concerns?

#javascript#localstorage#browser

0

1 reply

dev3 · Accepted answer

localStorage stores strings only. Assigning an object converts it with toString(), which gives "[object Object]". Serialise with JSON.

const settings = { theme: 'dark', fontSize: 14 };
localStorage.setItem('settings', JSON.stringify(settings));

const saved = JSON.parse(localStorage.getItem('settings') ?? 'null');

Safe helpers

export const store = {
  get(key, fallback = null) {
    try {
      const raw = localStorage.getItem(key);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback;           // blocked storage or corrupt JSON
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch {
      return false;              // quota exceeded or private mode
    }
  },
};

Facts

  • Limit is roughly 5 MB per origin (varies by browser).
  • Synchronous, so large reads block the main thread.
  • Persists until cleared; sessionStorage lasts for the tab session.
  • Not shared across origins (http vs https, subdomains).
  • Other tabs get a storage event when you change a key:
window.addEventListener('storage', (e) => { if (e.key === 'settings') reload(); });
  • Dates come back as strings; revive them manually.

Security

Anything in localStorage is readable by any script on the page, so an XSS bug can steal it. Do not store session tokens or secrets there; use HttpOnly cookies. Never trust stored values: validate them after parsing.

For bigger data

Use IndexedDB (via idb or Dexie) for structured or large data.

There is a ready-made React hook in the DEV3 snippet library.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.