Difficulty: Intermediate
Explain the browser Web APIs localStorage, sessionStorage and fetch. How do they differ, and how do you use them safely in a production app?
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 | 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.
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.HttpOnly, Secure, SameSite cookies.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:
response.ok (true for status 200-299). A 500 from the server will happily flow into response.json().headers: { 'Content-Type': 'application/json' } and JSON.stringify when posting JSON.credentials: 'include' and the matching CORS headers on the server.response.clone() if you truly need two reads.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.
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.
// 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.
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+.
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.
localStorage, sessionStorage, Fetch API, AbortController, Web Storage, response.ok