---
title: "How do I store an object in localStorage?"
description: "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."
url: https://www.danny.engineering/answer/javascript/how-do-i-store-an-object-in-localstorage
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Javascript"]
---

# How do I store an object in localStorage?

## 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.


```javascript
const settings = { theme: 'dark', fontSize: 16 };

localStorage.setItem('settings', JSON.stringify(settings));

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.


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


```javascript
export function saveJSON(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (error) {
    console.warn(`Could not save "${key}"`, error);
    return false;
  }
}

export function loadJSON(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    return raw === null ? fallback : JSON.parse(raw);
  } catch {
    return fallback;
  }
}

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.


```javascript
try {
  localStorage.setItem('draft', JSON.stringify(bigDraft));
} catch (error) {
  if (error instanceof DOMException && error.name === 'QuotaExceededError') {
    // Remove old entries, or tell the user the draft could not be saved
  }
}
```


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.


```javascript
const defaults = { theme: 'light', fontSize: 16, reduceMotion: false };
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.

## Related reading

- [MDN: Window.localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
- [MDN: Storage quotas and eviction criteria](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria)
