Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
A practical tour of the browser platform for frontend developers who mostly work in a framework. Covers the DOM and BOM, cancelling fetch requests with AbortController, choosing between cookies, localStorage, sessionStorage and IndexedDB, a small StorageManager that saves form drafts, microtasks vs tasks in the event loop, and Intersection Observer.

React, Vue, Svelte and Next.js hide much of the browser from you. That's useful until a bug lives in the platform, not the framework. This guide is for frontend developers who mostly work in a framework and want to understand the browser underneath it. You'll cover the object models, network requests you can cancel, the four ways to store data on the client, the event loop, and Intersection Observer. Along the way you'll build a small helper that keeps form drafts safe across a page reload.
This is part 9 of the Frontend & JavaScript Fundamentals series. It follows OOP principles and design patterns in JavaScript.
Key takeaways
- Cancel stale requests with
AbortController, and checkresponse.ok, becausefetch()doesn't reject on a 404 or 500. - Pick storage by lifetime and size: cookies for small data the server needs, Web Storage for small client data, IndexedDB for large or structured data.
- The event loop runs every queued microtask before the next task, so a promise loop that never ends can freeze the page.
Web APIs are the interfaces a browser gives JavaScript to work with the page, the network, storage and the device. Think of the browser as a small operating system: storage is its file system, the event loop is its scheduler, and fetch is its network I/O.
1. The object model: DOM vs BOM
Before the APIs, separate the two main interfaces you work with.
The Document Object Model (DOM)
The DOM is the tree of objects the browser builds from your HTML. Frameworks update it for you. React, for example, compares renders and only changes the DOM nodes that differ, as its "Render and Commit" guide explains.
Performance tip: web.dev explains that if you change a style and then read a layout value such as offsetHeight, the browser has to run layout right away. This is a forced synchronous layout. Doing it again and again in a loop is called layout thrashing. When you build animations or drag-and-drop, read all layout values first, then write.
The Browser Object Model (BOM)
This is everything outside the page content: the window, navigator, location and history objects. It's where the browser exposes the device and the tab.
- Navigator: gives you the user agent, the clipboard and
hardwareConcurrency. MDN describes the last one as the number of logical processors, which you can use to size a pool of Web Workers. - History:
history.pushState()adds an entry to the session history. MDN notes that the browser won't load the new URL when you call it. Single-page apps use this to change the URL without a full page load.locationis for reading the URL, or for real navigation.
2. Network requests: beyond Axios
Libraries such as Axios are still useful. But the native Fetch API now covers most of what small apps need, so you can often skip the extra dependency.
Calling await fetch() isn't the whole job, though. You need to handle cancellation and HTTP errors.
The AbortController
In search boxes and AI chat interfaces, users often change their input before the previous request finishes. If you don't cancel the old request, a slow old response can overwrite a fast new one. MDN says abort() can cancel fetch requests, response bodies and streams.
const controller = new AbortController();
const signal = controller.signal;
// Start a request
fetch('/api/heavy-data', { signal })
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', err);
}
});
// Cancel it if the user types again (or navigates away)
document.querySelector('#search')?.addEventListener('input', () => controller.abort());
MDN's fetch() reference lists AbortError as the error you get after abort(). It also notes that a fetch() promise does not reject on HTTP error codes such as 404. That's why the example checks response.ok; the earlier version of this post skipped that check.
3. Client-side storage
Apps need to keep state. Redux or Zustand hold state in memory, and it's gone after a refresh. You have four main options for keeping it longer.
Cookies
MDN notes that a browser usually limits each cookie to about 4KB. Cookies are sent with every request, which slows things down if you store a lot in them. MDN now recommends the Web Storage API and IndexedDB for client-side storage. As a rule of thumb, keep cookies for small values the server needs, such as a session id.
Local storage
localStorage keeps data even after the browser is closed and reopened. MDN's quota guide says browsers allow up to 5 MiB of local storage per origin. It's a good fit for UI preferences such as dark mode and other small settings.
MDN notes that Web Storage is synchronous: each call blocks other JavaScript until it's done. So keep the data small. It stores strings, so you serialize objects with JSON.stringify().
Session storage
sessionStorage has the same 5 MiB limit per origin and is separate for each tab. It survives a page reload. MDN says closing the tab destroys it. That makes it a good fit for form data in multi-step wizards, where you want to survive an accidental refresh but not keep the data next week.
IndexedDB
IndexedDB is a low-level API for storing significant amounts of structured data, including files, as MDN describes it. It's transactional and asynchronous, so it doesn't block the page. Quotas are much larger: in Chrome, an origin can use up to 60% of total disk size, per MDN. If you build a local-first app, IndexedDB is your client-side database.
| Option | Typical limit | Lasts until | Best for |
|---|---|---|---|
| Cookies | About 4KB per cookie | The expiry you set | Small values the server needs (session id) |
localStorage |
5 MiB per origin | You delete it | Preferences and small settings |
sessionStorage |
5 MiB per origin | The tab closes | Drafts and wizard steps |
| IndexedDB | A share of disk (browser-specific) | You delete it, or the browser evicts it | Large or structured data, offline apps |
4. Practical build: a resilient form
Here's a small helper that uses both sessionStorage and localStorage. It solves a common problem: losing what you typed when the page reloads by accident.
The helper saves draft data to sessionStorage on every keystroke, which suits frequent, short-lived writes. It can also save to localStorage for drafts you want to keep longer.
class StorageManager {
constructor(prefix = 'app_v1_') {
this.prefix = prefix;
}
// Helper to handle JSON serialization
_set(storageType, key, value) {
try {
const serialized = JSON.stringify(value);
window[storageType].setItem(this.prefix + key, serialized);
return true;
} catch (e) {
console.error('Could not save to storage (quota exceeded or value not serializable)', e);
return false;
}
}
_get(storageType, key) {
const item = window[storageType].getItem(this.prefix + key);
if (!item) return null;
try {
return JSON.parse(item);
} catch (e) {
return item;
}
}
// Session: For accidental refreshes
saveSession(key, value) {
return this._set('sessionStorage', key, value);
}
getSession(key) {
return this._get('sessionStorage', key);
}
// Local: For long-term preferences
savePermanent(key, value) {
return this._set('localStorage', key, value);
}
getPermanent(key) {
return this._get('localStorage', key);
}
}
// Usage Example
const storage = new StorageManager('draft_tool_');
// Imagine an input field listener
const inputField = document.querySelector('#blog-content');
if (inputField) {
// On load: Check if we have a session draft
const savedDraft = storage.getSession('current_post');
if (savedDraft) {
inputField.value = savedDraft;
console.log('Restored from session!');
}
// On Input: Save to session
inputField.addEventListener('input', (e) => {
storage.saveSession('current_post', e.target.value);
});
}
The if (inputField) guard keeps the script from throwing on pages without the field. MDN's quota guide says that when storage is full, browsers throw a QuotaExceededError, and you should catch it with try...catch. _set() does that. The prefix keeps your keys apart from other scripts on the same origin.
The draft now survives a reload. Because it lives in sessionStorage, it's gone once the tab is closed. To keep drafts across sessions, call savePermanent() instead.
5. The event loop and asynchronous JavaScript
The event loop explains why a page "freezes". JavaScript runs your code on one thread with one call stack.
When you call fetch or setTimeout, you don't block the stack. You hand the work to the browser, which queues your callback when the work is done.
Microtasks vs tasks (macrotasks)
Not all queues are equal.
- Tasks (often called macrotasks):
setTimeout,setInterval, I/O and user events. - Microtasks: promise callbacks (
.then,.catch,.finally),queueMicrotask()andMutationObservercallbacks.
The rule: MDN's microtask guide says that after each task, the browser runs microtasks until the queue is empty, and only then may it update the screen. Microtasks added by other microtasks run in the same pass. So a promise chain that keeps queuing more promises can block rendering for good. A recursive setTimeout lets the browser render between calls.
// Blocks rendering: the microtask queue never empties
function spin() {
queueMicrotask(spin);
}
// Lets the browser render between calls: each call is a new task
function tick() {
setTimeout(tick, 0);
}
6. Intersection Observer API
The old way to know when an element scrolled into view was a scroll listener that called getBoundingClientRect(). MDN explains that this code runs on the main thread and fires constantly while the user scrolls, which can make the page feel slow.
The Intersection Observer API hands this work to the browser. It tells you, asynchronously, when an element enters or leaves the viewport. MDN lists these common uses:
- Lazy loading images: fetch an image only when the user scrolls near it.
- Infinite scrolling: load more content when the user reaches a marker near the end of the list.
- Visibility reporting: check whether an element, such as an ad or a section of a post, was actually on screen.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is visible!');
// Load data or animate
entry.target.classList.add('fade-in');
// Stop observing once done
observer.unobserve(entry.target);
}
});
});
observer.observe(document.querySelector('.lazy-load-target'));
MDN notes that the callback still runs on the main thread, so keep it quick.
Build for the platform
Frameworks come and go. I spent years writing jQuery, then Angular, now React. The browser platform underneath was the common thread through all three.
When you know the storage APIs, the event loop and how to cancel network requests, your code depends less on any one framework. You stop fighting the browser and start using what it already gives you.
Next step: extend the StorageManager above. Add an expiry time to the localStorage items so the app cleans up after itself. Then read the next part, the JavaScript runtime and event loop explained, which goes deeper into the call stack and task queues.
Frequently asked questions
What is the difference between localStorage and sessionStorage?
Both store strings per origin, with a limit of about 5 MiB each. localStorage lasts until you delete it, even after the browser restarts. sessionStorage belongs to one tab and is destroyed when that tab closes.
When should I use IndexedDB instead of localStorage?
Use IndexedDB for large or structured data, files, or offline apps. It's asynchronous, so it doesn't block the page, and its quota is a share of the disk. Keep localStorage for small values such as preferences.
Does fetch throw an error on a 404?
No. MDN explains that a fetch() promise only rejects on network failures or a bad request, such as an invalid URL. For HTTP errors, check response.ok or response.status and throw your own error.
What is the difference between microtasks and macrotasks?
Tasks (macrotasks) include timers and user events, and the browser runs one at a time. Microtasks include promise callbacks and queueMicrotask(). After each task, the browser runs every queued microtask before it renders or starts the next task.
Should I still store auth tokens in cookies?
Cookies are still the usual place for a session id that the server reads. MDN recommends Web Storage and IndexedDB for other client-side data, because cookies are sent with every request. Frontend authentication with JWT and cookies covers the security trade-offs.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
- web.dev: Avoid large, complex layouts and layout thrashing
- react.dev: Render and Commit
- MDN: Navigator.hardwareConcurrency
- MDN: History.pushState()
- MDN: Window.fetch()
- MDN: AbortController
- MDN: Using HTTP cookies
- MDN: Web Storage API
- MDN: Storage quotas and eviction criteria
- MDN: IndexedDB API
- MDN: Using microtasks in JavaScript with queueMicrotask()
- MDN: Intersection Observer API
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...