Web Storage

Version and validate stored JSON

Serialize a small object deliberately, reject malformed or outdated data, and migrate its shape instead of trusting persisted strings.

8 minute lesson

~~~

Web Storage stores strings. JSON gives a string structure, not a guarantee that old or edited data is valid.

Add a version to the stored value. Parse inside try...catch, check the expected fields, and fall back safely. When the shape changes, migrate known older versions or discard replaceable data.

const raw = localStorage.getItem('field-notes:settings')
let settings = { version: 1, theme: 'light' }

try {
  const saved = JSON.parse(raw ?? 'null')
  if (saved?.version === 1 && ['light', 'dark'].includes(saved.theme)) {
    settings = saved
  }
} catch {}

Any script on the origin, a browser extension, or the user through DevTools can change this value. Treat it as untrusted input even though your application wrote it first.

Do not store authentication tokens here. An injected script running in the origin can read and exfiltrate JavaScript-accessible storage.

Save valid settings, malformed JSON, an unknown version, and a theme outside the allowlist. Prove startup uses a safe value in every case and never leaves the interface half-initialized.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →