# Web APIs (localStorage, fetch, etc.)

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-web-apis
Last updated: 2026-11-28

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

|  | `localStorage` | `sessionStorage` | Cookies |
| --- | --- | --- | --- |
| Lifetime | Until cleared by code or the user | Until the tab is closed | Until `Expires`/`Max-Age`, or session |
| Scope | Origin, shared by all tabs | Origin and that single tab | Domain and path |
| Sent to server | No | No | Yes, on every matching request |
| Typical size | About 5 MB per origin | About 5 MB per origin | About 4 KB per cookie |
| Readable by JS | Always | Always | Not 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

- **It is synchronous.** Every read and write blocks the main thread. Fine for a theme preference, bad for megabytes of data; use IndexedDB for that.
- **It can throw.** `setItem` throws a `QuotaExceededError` when full, and storage can be blocked or restricted in some privacy modes and embedded iframes. Wrap access in `try/catch`.
- **No expiry.** Unlike cookies there is no TTL, so you build one by storing a timestamp alongside the value.
- **Not for secrets.** Any script on the page, including an XSS payload or a compromised third-party widget, can read it. Session tokens are safer in `HttpOnly`, `Secure`, `SameSite` cookies.

### 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

- Web Storage stores strings only, is synchronous, and is scoped to the origin; sessionStorage is also scoped to the tab.
- Roughly 5 MB per origin; setItem throws QuotaExceededError when full, so wrap it in try/catch.
- Never keep auth tokens in localStorage if you can use an HttpOnly, Secure, SameSite cookie instead.
- fetch rejects only on network failure or abort; always check response.ok for HTTP errors.
- Use AbortController to cancel and AbortSignal.timeout(ms) to time out a fetch.

## Common follow-up questions

- What is the difference between localStorage and cookies from a security point of view?
- Why might you choose IndexedDB over localStorage?
- How do you send cookies with a cross-origin fetch, and what must the server do?
- How would you retry a failed fetch with exponential backoff?
- What does the storage event do, and in which tabs does it fire?

## Interview tips

- Mention the response.ok gotcha without being asked; interviewers use it to separate people who have shipped fetch code from those who have not.
- When asked where to store a JWT, discuss XSS versus CSRF trade-offs instead of giving a one-word answer.
- Bring up AbortController for search-as-you-type; it shows you think about race conditions.

## Concepts covered

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

Previous: [Event Delegation & Bubbling](https://www.internhack.in/learn/interview/javascript-interview/js-event-delegation) · Next: [Event Bubbling, Capturing & Event Flow](https://www.internhack.in/learn/interview/javascript-interview/js-event-bubbling) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Higher-Order Functions](https://www.internhack.in/learn/interview/javascript-interview/js-higher-order-functions)
- [Callback Hell & Async Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-callback-patterns)
- [Symbols & Well-Known Symbols](https://www.internhack.in/learn/interview/javascript-interview/js-symbols)
- [Proxy and Reflect API](https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect)
- [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset)
- [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
