More JavaScript answers

by Danny
Published 2 min read

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.


_10
const settings = { theme: 'dark', fontSize: 16 };
_10
_10
localStorage.setItem('settings', JSON.stringify(settings));
_10
_10
const 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.


_10
localStorage.setItem('user', { name: 'Ada' });
_10
localStorage.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.


_20
export 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
_20
export 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
_20
const 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.


_10
try {
_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.


_10
const defaults = { theme: 'light', fontSize: 16, reduceMotion: false };
_10
const 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. Date objects come back as strings, Map and Set become empty objects, and undefined values and functions are dropped. Convert them yourself, for example store dates with toISOString() and rebuild them with new Date(value).
  • Circular references. JSON.stringify throws a TypeError for an object that refers to itself. Save only the plain data you need.
  • Using it on the server. localStorage only 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 storage event on window to react to changes made in another tab.
#

Was this resource helpful?