ProgramGuru

Browser Storage APIs

Browser Storage APIs — why it matters

localStorage and sessionStorage expose a small string key/value API in browsers. Values are strings, so objects must be serialized and parsed. localStorage persists across browser sessions according to origin and browser policy; sessionStorage is scoped to a page session. Storage can be unavailable or throw, and neither is a safe place for secrets.

What you’ll learn

  • Explain browser storage apis and the problem it solves.
  • Identify the relevant compile-time checks and runtime responsibilities.
  • Run the example, predict its output, and try a realistic modification.

Understand the mechanism

The function relies on the relevant Storage method contracts. A Map-backed test double behaves like the small part of the browser API that this function needs; the separate browser demonstration uses actual localStorage.

Storage is synchronous and may throw (for example in restricted contexts). Do not rely on it for large data or sensitive tokens.

Follow the concept flow

Browser Storage APIs — concept flowStorage interface → Write string key/value → Read and fallbackBrowser Storage APIs1Storage interface2Write string key/value3Read and fallbackBrowser code needs browser APIs; Node code needs Node.js APIs.
Follow the responsibilities from input to checked result.

Run the primary TypeScript example

Save as browser-storage-apis.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.

TypeScript source

function storeSettings(store: Pick<Storage,"setItem"|"getItem">): string {
  store.setItem("theme", "dark");
  return store.getItem("theme") ?? "light";
}
const memory = new Map<string,string>();
console.log(storeSettings({
  setItem: (key, value) => { memory.set(key, value); },
  getItem: key => memory.get(key) ?? null,
}));

Verified output

dark

Compile: npx tsc --strict --target es2022 --module commonjs browser-storage-apis.ts; run: node browser-storage-apis.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.

The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.

Trace the result

The function relies on the relevant Storage method contracts. A Map-backed test double behaves like the small part of the browser API that this function needs; the separate browser demonstration uses actual localStorage.

Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.

Build the real browser interaction

Real browser lab: This TypeScript targets actual DOM APIs and was successfully type-checked against the DOM library. It requires a browser; its runtime interaction was not simulated in Node.js. Save the two files together, compile the TypeScript, and serve this folder through a local HTTP server such as python3 -m http.server 8000 (especially important for modules and workers).

index.html

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TypeScript browser lab</title></head><body>
<h1 id="title">TypeScript lesson</h1><button id="action">Run</button><p id="output"></p>
<script type="module" src="./app.js"></script>
</body></html>

app.ts

const button = document.querySelector<HTMLButtonElement>("#action");
const output = document.querySelector<HTMLElement>("#output");
button?.addEventListener("click", () => {
  try {
    localStorage.setItem("course-theme", "dark");
    if (output) output.textContent = localStorage.getItem("course-theme") ?? "light";
  } catch (error) {
    if (output) output.textContent = "Storage unavailable";
  }
});

Compile: npx tsc --strict --target es2022 --module es2022 --lib es2022,dom app.ts. For the worker example also compile worker.ts with --lib es2022,webworker. Then open the served HTML page in a browser to interact with it.

Common mistake and correction

Storage is synchronous and may throw (for example in restricted contexts). Do not rely on it for large data or sensitive tokens.

Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.

Practice the concept

Save a preference and restore it on page load. Handle malformed JSON and a disabled-storage exception.

Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.

Check your understanding

Which statement best describes the role of TypeScript and the actual runtime for this lesson?
Choose one answer. You can try again.

Answer and explanation

The described check or API works only within its stated environment and still needs the corresponding runtime behavior.

The function relies on the relevant Storage method contracts. A Map-backed test double behaves like the small part of the browser API that this function needs; the separate browser demonstration uses actual localStorage.

What to remember

localStorage and sessionStorage expose a small string key/value API in browsers.

Run the primary example, then complete the practice task or environment-specific lab.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Working with URLs and Query Parameters →