Skip to lesson content
Web Technologies › Level 19
LEVEL 19 · STORAGE

Browser Storage and Web APIs

Save and restore small preferences with explicit lifetimes, validation and failure handling.

💾 Storage🔤 JSON records🔑 One-key ownership🧪 Lab + MCQs
01

Learning Objectives

Lifetime

Choose memory, a page session or a longer-lived preference.

Data contract

Store text; parse and validate before accepting it.

Failures

Handle denied access and failed writes honestly.

Ownership

Use one named key and preserve other site data.

02

Memory and Persistence Are Different Decisions

const draft = new Map();
draft.set("study", "HTML for 15 minutes");
console.log(draft.get("study"));
// A freshly reloaded page creates a new Map.
03

Compare the Four Storage Choices

ChoiceTypical lifetimeUseful exampleImportant limit
JavaScript memoryCurrent script instanceUnsaved previewA reload creates fresh state
localStorageCan survive reloads and browser restartsSmall study preferenceUser settings, clearing and policy affect availability
sessionStoragePage session, partitioned by origin and tabTab-specific draftNot a server login session
CookieSession or configured expiryServer session identifierRequest scope and security attributes matter
04

Origins, Paths and Storage Scope

Locate a stored preference
Origin

Scheme + host + port selects the area.

Backend

Local and session storage are separate areas.

Key

One feature-specific key identifies the record.

Value

A JSON string represents the controlled preference.

const key = "codebhavya-wt19-storage-lab-v1";
// Same-origin paths can share this localStorage key.
// sessionStorage uses a different area for the same key text.
05

localStorage — Remember a Small Preference

try {
  const store = window.localStorage;
  store.setItem("study-topic", "html");
  const topic = store.getItem("study-topic");
  store.removeItem("study-topic");
} catch (error) {
  console.error("Preference storage unavailable", error.name);
}
06

sessionStorage — A Page Session, Not a Login

try {
  window.sessionStorage.setItem("draft-topic", "css");
  console.log(window.sessionStorage.getItem("draft-topic"));
} catch (error) {
  console.error("Draft storage unavailable", error.name);
}
07

Strings, JSON and Missing Values

const preference = {
  version: 1, topic: "html", minutes: 15, note: "Review forms"
};
const text = JSON.stringify(preference);
// After reading: distinguish null from stored text.
if (text !== null) {
  const parsed = JSON.parse(text);
  console.log(parsed.topic);
}
08

Validate the Record and Its Version

if (record.version !== 1) throw new Error("Unsupported version");
if (![15, 30, 45].includes(record.minutes)) {
  throw new Error("Invalid study duration");
}
// Also check object shape, topic and bounded note.
// Only then update editor fields.
09

Denied Access, Quotas and Honest Feedback

try {
  store.setItem(key, JSON.stringify(validated));
  showStatus("Saved in the selected storage area.");
} catch (error) {
  showStatus("Save failed: " + error.name);
}
10

Delete One Key and Keep Other Features Intact

store.removeItem("codebhavya-wt19-storage-lab-v1");
// Preserve unrelated keys, including course completion.
output.textContent = rawText;
// Display saved text as text, rather than HTML.
11

Storage Events and Unsaved Work

window.addEventListener("storage", event => {
  if (event.storageArea !== window.localStorage) return;
  if (event.key !== key && event.key !== null) return;
  showStatus("Saved data changed elsewhere. Load to inspect.");
});
12

Cookies — Data Attached to Matching Requests

Set-Cookie: session_id=opaque-example; Path=/; Secure; HttpOnly; SameSite=Lax
13

Other Browser APIs — Choose by the Task

Choose a capability
Small preference

Web Storage with a bounded record.

Structured collection

An asynchronous database such as IndexedDB.

Response resources

A deliberate Cache API strategy.

Navigation data

URL parsing and history state.

14

Privacy and Trust Boundaries

Minimize

Keep only fields required by the learning task.

Explain

Show the selected backend and the exact key.

Remove

Provide a button that deletes this feature’s record.

Recheck

Validate whenever saved text enters the editor.

15

Design the Save and Load Lifecycle

Preference lifecycle
Edit

The draft may differ from saved data.

Save

Validate, serialize, then attempt one-key write.

Load

Read, distinguish absence, parse and validate.

Delete / reset

Delete saved key or reset editor, explicitly.

16

Premium Visualizer — Save and Restore a Preference

Follow a normal preference through edit, validation, serialization, reading and restoration. The five-stage player keeps the same visual style and controls as the previous lessons. The lab below separately exercises missing data and failed operations.

BROWSER STORAGE TRACE
Step 1 of 5
STEP 01

Prepare a study preference

The editor holds a draft; nothing has been saved yet.

{ version: 1, topic: "html", minutes: 15, note: "Review forms" }

What is happening?

Changing fields does not write storage. Select the area and explicitly press Save.

17

Premium Interactive — Study Preference Storage Lab

Leave the note empty or use a short learning reminder. The saved record version is 1.

Memory mode. No preference has been read or saved.

Last operation output

No operation yet.

JSON contract checker · does not write storage

Try the sample, an unknown version, a string duration or malformed JSON.

No JSON checked yet.
18

Debugging — Find the Storage Boundary

Wrong area

Confirm origin, backend and exact key before assuming data disappeared.

Bad JSON

Distinguish missing text, malformed JSON and an unacceptable record.

Failed write

Check the caught error; do not report success or switch areas silently.

Too much cleanup

Remove the one owned key, rather than clearing the whole origin.

19

Interview Questions — Flip to Explain

QUESTION

Does localStorage automatically synchronize with a server?

Click or press Enter to explain
ANSWER

No. It stores strings in an applicable browser storage area. Server or account synchronization needs a separate implemented flow.

QUESTION

What does getItem return for an absent key?

Click or press Enter to explain
ANSWER

Null. A present string such as "null" or an empty string is a different case.

QUESTION

Why validate after JSON.parse?

Click or press Enter to explain
ANSWER

Parsing accepts many JSON values. The application still needs the supported version, fields, types and bounds.

QUESTION

Can sessionStorage authenticate a user?

Click or press Enter to explain
ANSWER

No. A local boolean is not a server-authorized login or permission decision.

QUESTION

Why catch access to window.localStorage itself?

Click or press Enter to explain
ANSWER

Obtaining the storage area can fail, before getItem or setItem is called.

QUESTION

Why avoid storage.clear in a lesson?

Click or press Enter to explain
ANSWER

It removes every key in that area, including other site features. Remove only the lab key.

QUESTION

Does the writer receive its own storage event?

Click or press Enter to explain
ANSWER

No. Other documents sharing the changed area can receive the notification.

QUESTION

What does HttpOnly do for a cookie?

Click or press Enter to explain
ANSWER

It prevents JavaScript access to that cookie. A server sets it through a response header; it does not replace server-side authorization.

20

MCQ Practice — Choose the Storage Behavior

PRACTICE

1. What happens to a new Map after a fresh page reload?

PRACTICE

2. What does getItem return when the key is absent?

PRACTICE

3. Which is the lab’s accepted duration?

PRACTICE

4. What should happen after loading version 2 in this version 1 lab?

PRACTICE

5. What does Reset fields do here?

PRACTICE

6. Which cleanup preserves other site features?

PRACTICE

7. What does the simulated quota mode block?

PRACTICE

8. Who receives a localStorage change event?

PRACTICE

9. How should an external change affect an unsaved editor here?

PRACTICE

10. Which cookie attribute prevents JavaScript reading it?

PRACTICE

11. Are Web Storage values automatically included in HTTP request headers?

PRACTICE

12. What should a failed Save report?

21

Extra Practice — Observe Specific Storage Outcomes

Memory reload

Save in memory, reload, then Load memory. Expected: no record in the new instance.

Local reload

Save CSS/30 in local mode, reset fields, then Load. Expected: CSS/30 restored; verify after reload too.

Session reload

Save JavaScript/45 in session mode and reload the same tab. Expected: Load restores it if the area remains available.

Quota

Save a normal record, then change the note and simulate quota. Expected: Save fails; normal Load returns the earlier record.

Blocked

Select blocked access and try Save/Load/Inspect/Delete. Expected: each fails and editor fields stay intact.

Wrong shape

Check JSON with version 2, minutes "30", null and malformed text. Expected: each rejects without writing storage.

Narrow delete

Delete in local mode, then Load local and session. Expected: local missing; an independently saved session record remains.

Another tab

  • In two same-origin tabs use normal local mode.
  • Save a changed note in one.
  • Expected: other tab announces change while preserving its draft.
22

Quick Revision

Memory: Fresh script instances begin with fresh memory.
Local: Can retain small preferences; availability is not guaranteed.
Session: Partitioned by origin and top-level browsing context.
Text: Serialize simple records with JSON.
Contract: Validate version, shape, types and bounds.
Failure: Catch getter and method errors.
Key: Namespace one feature’s record.
Delete: Remove only the key you own.
Event: Other sharing documents receive change notices.
Cookie: Request-sending rules differ from Web Storage.
23

Glossary — Flip to Learn

TERM

Persistence

Click to see meaning
DEFINITION

Persistence

Keeping data beyond a current script instance, subject to the chosen storage lifecycle.

TERM

Origin

Click to see meaning
DEFINITION

Origin

The combination of scheme, host and port used in browser access boundaries.

TERM

localStorage

Click to see meaning
DEFINITION

localStorage

A synchronous string key/value area that can retain data beyond reloads.

TERM

sessionStorage

Click to see meaning
DEFINITION

sessionStorage

A synchronous string key/value area partitioned by origin and top-level browsing context.

TERM

Serialization

Click to see meaning
DEFINITION

Serialization

Converting a supported record into a text representation such as JSON.

TERM

Record version

Click to see meaning
DEFINITION

Record version

A field identifying the application data format expected by a loader.

TERM

Quota error

Click to see meaning
DEFINITION

Quota error

A failed attempt to write when the selected area cannot accommodate the operation.

TERM

Storage event

Click to see meaning
DEFINITION

Storage event

A notification to other documents sharing an area that its data changed.

TERM

Cookie

Click to see meaning
DEFINITION

Cookie

A browser-managed value that can accompany matching HTTP requests.

TERM

HttpOnly

Click to see meaning
DEFINITION

HttpOnly

A cookie attribute that prevents JavaScript access to that cookie.

24

Final Challenge — A Defensive Preference Store

25

Level 19 Complete?

Before marking complete, compare the storage lifetimes, restore one valid preference, reject a bad record and explain narrow deletion plus honest failure feedback. Completion is a local study marker rather than a score.