JSON and localStorage Patterns

July 23, 20268 min read

Why JSON Works Well With localStorage

The browser's localStorage API stores strings only, which makes JSON the natural choice for saving structured data. Preferences, cached API results, drafts, and small application state can all be serialized cleanly.

1. Wrap Serialization in Helpers

function save(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function load(key, fallback = null) {
  const raw = localStorage.getItem(key);
  if (raw === null) return fallback;
  try {
    return JSON.parse(raw);
  } catch {
    return fallback;
  }
}

2. Store Small Data Only

localStorage is convenient, but it is not a database. Keep the data small and infrequently changing. Good candidates include theme settings, UI state, and cached preferences.

3. Handle Parse Failures Safely

A corrupted or manually edited value should not break your app. Always provide a fallback value when parsing fails. If the data format needs inspection, use the JSON Beautifier to review it first.

4. Version Your Stored Data

For anything more complex than simple preferences, store a version number alongside the payload. This makes migrations much easier when the shape of the data changes.

5. Clear Expired Cache Entries

If you're using JSON for cached API responses, include a timestamp and invalidate stale entries on load. That keeps localStorage from becoming a source of outdated state.

Conclusion

JSON plus localStorage is a simple and effective browser persistence pattern. Keep the data small, wrap parsing carefully, and version your payloads when your app grows.

Related Articles