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
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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
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');
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
}
},
};
sessionStorage lasts for the tab session.storage event when you change a key:window.addEventListener('storage', (e) => { if (e.key === 'settings') reload(); });
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.
Use IndexedDB (via idb or Dexie) for structured or large data.
There is a ready-made React hook in the DEV3 snippet library.