Web APIs (localStorage, fetch, etc.)

Difficulty: Intermediate

Question

Explain the browser Web APIs localStorage, sessionStorage and fetch. How do they differ, and how do you use them safely in a production app?

Answer

localStorage and sessionStorage are the two Web Storage APIs: synchronous key-value stores that only hold strings and are scoped to an origin. localStorage survives browser restarts, while sessionStorage lives only as long as that tab. fetch() is the Promise-based API for HTTP requests; it resolves for any HTTP response (including 404 and 500) and rejects only on network failure or abort, so you must check response.ok yourself.

localStorage vs sessionStorage vs cookies

localStoragesessionStorageCookies
LifetimeUntil cleared by code or the userUntil the tab is closedUntil Expires/Max-Age, or session
ScopeOrigin, shared by all tabsOrigin and that single tabDomain and path
Sent to serverNoNoYes, on every matching request
Typical sizeAbout 5 MB per originAbout 5 MB per originAbout 4 KB per cookie
Readable by JSAlwaysAlwaysNot if HttpOnly

Both storage objects expose the same methods: setItem, getItem (returns null when missing), removeItem, clear, key(i) and length. Values are always coerced to strings, so setItem('n', 5) stores "5" and objects must go through JSON.stringify and JSON.parse. A storage event fires in other tabs of the same origin when localStorage changes, which is a cheap way to sync a logout across tabs.

Gotchas with Web Storage

How fetch works and where people get it wrong

fetch(url, options) returns a Promise for a Response. The body is a stream that you read once with response.json(), .text(), .blob() or by iterating response.body. Common mistakes:

  1. Not checking response.ok (true for status 200-299). A 500 from the server will happily flow into response.json().
  2. Forgetting headers: { 'Content-Type': 'application/json' } and JSON.stringify when posting JSON.
  3. Expecting cookies on cross-origin calls without credentials: 'include' and the matching CORS headers on the server.
  4. Reading the body twice. Use response.clone() if you truly need two reads.

Cancelling and timing out requests

Pass an AbortSignal in the signal option. AbortController lets you cancel manually (for example, the previous search request when the user types another letter), and AbortSignal.timeout(ms) gives you a ready-made timeout signal that rejects with a TimeoutError. A manual abort() rejects with an AbortError. AbortSignal.any([...]) combines several signals. Cancelling stale requests is what prevents the classic race where an older, slower response overwrites newer results.

Real-world usage

On a Flipkart-style product page you might keep the recently viewed list in localStorage, a half-filled checkout form in sessionStorage so it survives a refresh but not a new tab, and call the cart API with fetch plus a timeout so a slow network does not leave the spinner running forever. Related browser APIs worth naming in an interview: IndexedDB for large structured data, IntersectionObserver for lazy loading, Web Workers for heavy computation, and the Cache API for offline support with service workers.

fetch and timers on the event loop. fetch returns a pending promise at once; its .then runs as a microtask when the response arrives.
  1. fetch returns immediately: The request runs in the browser's network layer.
  2. Timers run in Web APIs too: setTimeout callbacks join the task queue when due.
  3. Response → microtask: When the response arrives, the .then callback is queued as a microtask.
  4. Output: start, end, 0ms, 100ms, response.

Code examples

Safe JSON storage helpers with TTL

// Wrap Web Storage so a full quota or blocked storage never crashes the app
function setJSON(key, value, ttlMs) {
  const record = { value, expiry: ttlMs ? Date.now() + ttlMs : null };
  try {
    localStorage.setItem(key, JSON.stringify(record));
    return true;
  } catch (err) {
    console.warn('Storage write failed:', err.name); // e.g. QuotaExceededError
    return false;
  }
}

function getJSON(key, fallback = null) {
  try {
    const raw = localStorage.getItem(key);
    if (raw === null) return fallback;
    const { value, expiry } = JSON.parse(raw);
    if (expiry && Date.now() > expiry) {
      localStorage.removeItem(key); // lazily evict expired entries
      return fallback;
    }
    return value;
  } catch {
    return fallback; // corrupt JSON or storage unavailable
  }
}

setJSON('recentlyViewed', ['iphone-16', 'boat-airdopes'], 24 * 60 * 60 * 1000);
console.log(getJSON('recentlyViewed'));
console.log(getJSON('missing', []));

// Keep tabs in sync: fires in OTHER tabs of the same origin
window.addEventListener('storage', (e) => {
  if (e.key === 'auth' && e.newValue === null) location.assign('/login');
});

Storing an expiry next to the value adds the TTL that Web Storage lacks, and try/catch keeps quota or privacy-mode errors from breaking the page. The storage event lets one tab react to a logout in another.

fetch wrapper with status check, JSON body and timeout

class HttpError extends Error {
  constructor(response) {
    super(`HTTP ${response.status} ${response.statusText}`);
    this.name = 'HttpError';
    this.status = response.status;
  }
}

async function api(path, { body, timeoutMs = 8000, ...options } = {}) {
  const response = await fetch(path, {
    ...options,
    method: options.method ?? (body ? 'POST' : 'GET'),
    headers: { 'Content-Type': 'application/json', ...options.headers },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(timeoutMs), // rejects with TimeoutError
  });

  // fetch resolves for 404/500, so check explicitly
  if (!response.ok) throw new HttpError(response);
  return response.status === 204 ? null : response.json();
}

try {
  const cart = await api('/api/cart/items', { body: { sku: 'SKU123', qty: 1 } });
  console.log('Cart total (paise):', cart.totalPaise);
} catch (err) {
  if (err.name === 'TimeoutError') console.log('Server is slow, try again');
  else if (err instanceof HttpError) console.log('Server said', err.status);
  else console.log('Network problem:', err.message);
}

One wrapper handles the three failure modes separately: timeouts, non-2xx responses and network errors. AbortSignal.timeout is supported in all modern browsers and Node 18+.

Cancel stale search requests with AbortController

let controller = null;

async function search(query) {
  controller?.abort();              // cancel the previous in-flight request
  controller = new AbortController();

  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
      signal: controller.signal,
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    renderResults(await res.json());
  } catch (err) {
    if (err.name === 'AbortError') return; // expected, a newer search replaced it
    showError(err);
  }
}

// Typing "pho" fires three searches; only the last one renders
search('p');
search('ph');
search('pho');

Aborting the previous request guarantees that an older, slower response can never overwrite newer results. encodeURIComponent keeps characters like & and # from breaking the query string.

Key points

Common follow-up questions

Interview tips

Concepts covered

localStorage, sessionStorage, Fetch API, AbortController, Web Storage, response.ok

More JavaScript Interview questions