Web Storage
Save a small preference
Store and restore one replaceable string preference with localStorage without turning it into an application database.
8 minute lesson
localStorage fits a small preference that should survive a browser restart. Our theme is a good example.
The API is synchronous and stores strings. Write the preference when it changes, then read it during startup. A missing key returns null, so define a safe default.
localStorage.setItem('field-notes:theme', 'dark')
const theme = localStorage.getItem('field-notes:theme') ?? 'light'
document.documentElement.dataset.theme = theme
Prefix keys with the application and feature. This prevents a generic key such as theme from colliding with another script on the same origin.
Keep this startup read small. Web Storage blocks JavaScript while it reads or writes. IndexedDB is the better choice for a growing collection.
Only accept known theme values before applying them. A persisted string is input, not trusted configuration.
Save a theme, reload, and prove it returns. Then delete the key and prove the default applies without throwing or rendering an invalid value.
Lesson completed