Web Development Pro | Lesson 037 | Local Storage and Recoverable Persistence
Web Development Pro · Lesson 37 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 36 first. This lesson builds on serialization, versions, and failure handling. By the end, you can store harmless preferences while recovering from blocked or corrupted storage. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Save only a harmless preference
A visitor may want the directory to remember a category choice on the same device. LocalStorage stores string values associated with an origin and can persist across browser sessions. It is useful for small non-sensitive preferences, but it is not a secure database, a cross-device account, or a guarantee of permanent storage.
This exercise saves only one public category value after an explicit “Save category on this device” action. It does not store names, contact details, credentials, tokens, or search text. The narrow scope makes the feature understandable and reduces the consequences of a shared device or a storage leak.
Use a namespaced, versioned record
Choose a key that belongs to this application, such as workshop-demo:preferences. Store a JSON object containing a schema version and the category. Versioning lets future code distinguish a known shape from an older or incompatible one. Do not assume every string already stored under a key is valid merely because your own code originally wrote it.
File preferences.mjs:
const KEY = 'workshop-demo:preferences';
const categories = ['all', 'repair', 'textiles'];
export function readPreferences(storage) {
try {
const raw = storage.getItem(KEY);
if (raw === null) return { category: 'all' };
const value = JSON.parse(raw);
if (value === null || typeof value !== 'object' || value.version !== 1 ||
!categories.includes(value.category)) return { category: 'all' };
return { category: value.category };
} catch {
return { category: 'all' };
}
}
export function writePreferences(storage, category) {
if (!categories.includes(category)) return false;
try {
storage.setItem(KEY, JSON.stringify({ version: 1, category }));
return true;
} catch {
return false;
}
}
export function clearPreferences(storage) {
try { storage.removeItem(KEY); return true; }
catch { return false; }
}
The helper accepts a storage object rather than reading the global directly. Tests can provide an in-memory implementation or one that throws. The browser entry obtains window.localStorage inside its own try/catch because access to that property can itself fail before any helper method is called.
Recover without breaking the core task
Storage can be unavailable, full, blocked by policy, cleared by the user, or contain malformed JSON. Reading falls back to the harmless default. Writing returns false so the interface can explain that the choice still works for the current page but could not be saved. A preference failure should not prevent browsing workshops.
The reader does not silently overwrite malformed or unknown-version data. It simply returns the default until the user explicitly saves a supported record. This avoids destructive assumptions about future formats. A larger application might migrate known old versions, but every migration needs a defined input and output contract.
Remove only the application's own key when clearing this preference. Calling storage.clear() would remove other values for the same origin, potentially affecting unrelated features. Namespacing and targeted removal make cleanup safer and easier to explain.
Understand the storage boundary
An origin is based on scheme, host, and port. A development site at one port can have different local storage from the same host at another port. HTTP and HTTPS are also different origins. File-URL storage behavior is not a reliable deployment model, so use the local HTTP workflow from the module lessons.
LocalStorage operations are synchronous. Small preferences are a reasonable use, while large datasets or frequent writes during typing can block useful main-thread work. Do not persist every keystroke merely because the API is simple. Save at a deliberate moment that matches the user's expectation.
Other scripts running with access to the same origin may be able to read these values. An XSS vulnerability can expose local storage, which is one reason not to keep private credentials there. Storage is also local to the browser profile, not an identity check. A saved category says nothing about who is currently using the device.
Keep feedback accurate
After a successful save, say that the category was saved on this device. Do not claim it is backed up, synchronized, or permanently retained. After a failure, say that saving was unavailable and keep the current choice usable. The return value from writePreferences exists so the interface can distinguish those outcomes.
Clearing should also report failure honestly. If removeItem throws, resetting the current select to all does not prove the saved value was removed. The supplied interface distinguishes the current choice from persistent storage so a later reload does not contradict an overstated “cleared forever” message.
Test failure paths as first-class behavior
The tests cover missing storage, valid data, malformed JSON, an unsupported version, an unknown category, a throwing getter method, a throwing write, and a throwing removal. They also verify that only the namespaced key is touched and that another stored key survives clearing.
An in-memory test double exercises the helper's contract; it does not prove a particular browser's quota, private-browsing behavior, or persistence across restarts. Test the real browser path separately and make sure the directory remains useful when storage is disabled. Persistence is an enhancement, not a prerequisite for the core task.
Worked practice
Worked exercise 1: Handle corrupt data
Task: The saved string is '{broken'. Worked answer: JSON parsing throws, the reader catches it, and the page uses category all. The directory should still work. Do not crash the whole app or claim that the old preference was successfully restored.
Worked exercise 2: Clear only your preference
Task: Another feature stores its own key on the same origin. Worked answer: call removeItem for workshop-demo:preferences, not clear. The unrelated key should remain, and the test should verify that behavior explicitly.
Worked exercise 3: Report an unavailable save
Task: setItem throws because storage is unavailable. Worked answer: keep the selected category in the current interface, return false from the helper, and tell the visitor it could not be saved on this device. Do not discard the active filter merely because persistence failed.
Knowledge check
Question 1
What kind of data is appropriate for this example's storage? A) A harmless public category preference. B) A private API key. C) A session credential. D) An attendee contact list.
Check question 1: answer and explanation
Answer: A. The feature deliberately limits itself to non-sensitive preference data.
Question 2
Why include version: 1? A) To make every stored record automatically compatible with future code. B) To identify the expected stored schema. C) To migrate unknown formats without a migration rule. D) To guarantee browser retention.
Check question 2: answer and explanation
Answer: B. Versioning supports explicit handling of compatible and incompatible shapes.
Question 3
What should happen when reading storage fails? A) The whole site must stop. B) The last value is assumed valid. C) The harmless default should preserve the core task. D) Every origin key should be deleted.
Check question 3: answer and explanation
Answer: C. Persistence failure should degrade gracefully.
Question 4
Why avoid storage.clear for this operation? A) It removes only keys used by the currently executing module. B) It clears only values whose JSON version matches the current version. C) It restores deleted preferences automatically on the next read. D) It can remove unrelated origin data.
Check question 4: answer and explanation
Answer: D. Targeted removal respects the feature's limited ownership.
Question 5
What does a successful setItem call fail to guarantee? A) Permanent retention or cross-device synchronization. B) That the supplied helper returned true. C) That serialization was attempted. D) That the named key was used.
Check question 5: answer and explanation
Answer: A. Browser storage can later be cleared and is not an account-backed sync service.