localStorage only stores strings, so convert objects with JSON.stringify and read them back with JSON.parse. Handle missing keys, bad data and quota errors safely.
The short answer
#localStorage can only store strings. Turn the object into JSON with JSON.stringify before saving, and turn it back with JSON.parse when reading. Wrap both in try...catch, because reading can hit bad data and writing can run out of space.
_10const settings = { theme: 'dark', fontSize: 16 };_10_10localStorage.setItem('settings', JSON.stringify(settings));_10_10const saved = JSON.parse(localStorage.getItem('settings') ?? 'null');
Why it happens
#The Web Storage API stores key and value pairs, and both are always strings. If you pass anything else, the browser calls String() on it first. For a plain object that gives the useless string '[object Object]', which is why so many people find their saved data has vanished.
_10localStorage.setItem('user', { name: 'Ada' });_10localStorage.getItem('user'); // '[object Object]'
JSON is the standard way to turn objects, arrays, numbers and booleans into a string and back again.
How to fix it
#Write small helper functions
Keeping the conversion and error handling in one place stops every caller from repeating it.
_20export function saveJSON(key, value) {_20 try {_20 localStorage.setItem(key, JSON.stringify(value));_20 return true;_20 } catch (error) {_20 console.warn(`Could not save "${key}"`, error);_20 return false;_20 }_20}_20_20export function loadJSON(key, fallback) {_20 try {_20 const raw = localStorage.getItem(key);_20 return raw === null ? fallback : JSON.parse(raw);_20 } catch {_20 return fallback;_20 }_20}_20_20const settings = loadJSON('settings', { theme: 'light', fontSize: 16 });
getItem returns null for a key that does not exist, so check for that before parsing. The catch in loadJSON covers corrupted or hand-edited values that are not valid JSON.
Handle the storage limit
Browsers give each origin a limited amount of localStorage, commonly around 5 MB. When a write would go over it, setItem throws a DOMException named QuotaExceededError. It can also throw when storage is disabled by the user's settings.
_10try {_10 localStorage.setItem('draft', JSON.stringify(bigDraft));_10} catch (error) {_10 if (error instanceof DOMException && error.name === 'QuotaExceededError') {_10 // Remove old entries, or tell the user the draft could not be saved_10 }_10}
For large or structured data, IndexedDB is a better fit. It is asynchronous, can store much more, and keeps objects without converting them to strings.
Merge saved data with defaults
When you add a new setting later, older saved objects will not have it. Spread the defaults first so missing fields are filled in.
_10const defaults = { theme: 'light', fontSize: 16, reduceMotion: false };_10const settings = { ...defaults, ...loadJSON('settings', {}) };
For larger changes, store a version number alongside the data and migrate old shapes when you load them.
Common pitfalls
#- Values JSON cannot represent.
Dateobjects come back as strings,MapandSetbecome empty objects, andundefinedvalues and functions are dropped. Convert them yourself, for example store dates withtoISOString()and rebuild them withnew Date(value). - Circular references.
JSON.stringifythrows aTypeErrorfor an object that refers to itself. Save only the plain data you need. - Using it on the server.
localStorageonly exists in the browser. In server-rendered frameworks, read it inside an effect or event handler, not during render. - Storing secrets. Any script on the page can read
localStorage, including injected ones. Do not keep tokens or personal data there if you can avoid it. - Blocking the main thread. Reads and writes are synchronous. Writing a large object on every keystroke can make typing feel slow, so debounce saves.
- Expecting it to sync between tabs instantly. Other tabs do not see new values in variables they already hold. Listen for the
storageevent onwindowto react to changes made in another tab.
Related reading
#Was this resource helpful?