| 1 | --- |
| 2 | title: Version and Minimize localStorage Data |
| 3 | impact: MEDIUM |
| 4 | impactDescription: prevents schema conflicts, reduces storage size |
| 5 | tags: client, localStorage, storage, versioning, data-minimization |
| 6 | --- |
| 7 | |
| 8 | ## Version and Minimize localStorage Data |
| 9 | |
| 10 | Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. |
| 11 | |
| 12 | **Incorrect:** |
| 13 | |
| 14 | ```typescript |
| 15 | // No version, stores everything, no error handling |
| 16 | localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) |
| 17 | const data = localStorage.getItem('userConfig') |
| 18 | ``` |
| 19 | |
| 20 | **Correct:** |
| 21 | |
| 22 | ```typescript |
| 23 | const VERSION = 'v2' |
| 24 | |
| 25 | function saveConfig(config: { theme: string; language: string }) { |
| 26 | try { |
| 27 | localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) |
| 28 | } catch { |
| 29 | // Throws in incognito/private browsing, quota exceeded, or disabled |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | function loadConfig() { |
| 34 | try { |
| 35 | const data = localStorage.getItem(`userConfig:${VERSION}`) |
| 36 | return data ? JSON.parse(data) : null |
| 37 | } catch { |
| 38 | return null |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Migration from v1 to v2 |
| 43 | function migrate() { |
| 44 | try { |
| 45 | const v1 = localStorage.getItem('userConfig:v1') |
| 46 | if (v1) { |
| 47 | const old = JSON.parse(v1) |
| 48 | saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) |
| 49 | localStorage.removeItem('userConfig:v1') |
| 50 | } |
| 51 | } catch {} |
| 52 | } |
| 53 | ``` |
| 54 | |
| 55 | **Store minimal fields from server responses:** |
| 56 | |
| 57 | ```typescript |
| 58 | // User object has 20+ fields, only store what UI needs |
| 59 | function cachePrefs(user: FullUser) { |
| 60 | try { |
| 61 | localStorage.setItem('prefs:v1', JSON.stringify({ |
| 62 | theme: user.preferences.theme, |
| 63 | notifications: user.preferences.notifications |
| 64 | })) |
| 65 | } catch {} |
| 66 | } |
| 67 | ``` |
| 68 | |
| 69 | **Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. |
| 70 | |
| 71 | **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. |
| 72 |