| 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" |
| 17 | const data = localStorage |
| 18 | ``` |
| 19 | |
| 20 | **Correct:** |
| 21 | |
| 22 | ```typescript |
| 23 | const VERSION = " |
| 24 | |
| 25 | function saveConfig(config: |
| 26 | try { |
| 27 | localStorage.setItem(`userConfig: |
| 28 | } catch { |
| 29 | // Throws in incognito/private browsing, quota exceeded, or disabled |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | function loadConfig() { |
| 34 | try { |
| 35 | const data = |
| 36 | return data ? |
| 37 | } catch { |
| 38 | return null; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Migration from v1 to v2 |
| 43 | function migrate() { |
| 44 | try { |
| 45 | const v1 = |
| 46 | if (v1) { |
| 47 | const old = |
| 48 | saveConfig({ theme: |
| 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: |
| 60 | try { |
| 61 | localStorage.setItem( |
| 62 | "prefs:v1", |
| 63 | JSON.stringify({ |
| 64 | theme: user.preferences |
| 65 | notifications: user.preferences |
| 66 | }), |
| 67 | ); |
| 68 | } catch {} |
| 69 | } |
| 70 | ``` |
| 71 | |
| 72 | **Always wrap in try-catch:** `getItem() |
| 73 | |
| 74 | **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. |