Modern web browsers ship with over a hundred built-in APIs that enable everything from HTTP requests and persistent storage to video capture and cryptographic operations. These APIs are the bridge between your JavaScript code and the underlying operating system — they let you store data offline, stream real-time updates, record video, generate hashes, observe DOM changes, and much more. Yet many developers only scratch the surface, reaching for libraries when the platform already provides native solutions that are faster, smaller, and better integrated.
Our free interactive Web APIs cheat sheet provides eighty-five-plus copyable code examples organized into six categories: Fetch & Network, Storage, Workers, Observers, Media & Input, and Utilities. The Satellite Uplink Station aesthetic uses deep space-black backgrounds, signal-green and transmission-blue accents, and a subtle data-packet pulse animation — reinforcing the idea that every API call is a signal traveling through the browser's internal network. Everything runs in your browser. No server, no signup, no data collection.
Why Web APIs Matter
Before npm install became the default reflex for every problem, developers built entire applications with nothing but the platform. The modern browser is an extraordinarily capable runtime. IndexedDB stores megabytes of structured data. Service Workers intercept network requests and serve offline experiences. The Web Crypto API performs encryption without external dependencies. IntersectionObserver drives lazy loading without scroll listeners. These APIs are maintained by browser vendors, documented by standards bodies, and optimized at the engine level.
Understanding the built-in APIs provides three advantages. First, you write less code by avoiding dependencies that duplicate platform features. Second, your applications are more reliable because platform APIs do not break on minor version updates. Third, your bundle sizes shrink, improving load times and Core Web Vitals. A developer who knows when to use fetch versus XMLHttpRequest, when to choose localStorage versus IndexedDB, and when to reach for a Web Worker can build faster applications with fewer dependencies.
Fetch & Network
The Fetch API is the modern standard for HTTP requests. It returns Promises, supports streaming, and integrates cleanly with AbortController for cancellation. XMLHttpRequest remains relevant for progress tracking and synchronous requests (though the latter is discouraged). WebSockets enable persistent bidirectional connections for real-time applications. Server-Sent Events provide one-way server-to-client streaming over HTTP with automatic reconnection. The Beacon API reliably sends analytics data during page unload.
fetch() Basics
The simplest fetch call performs a GET request and returns a Response object. Always check response.ok before parsing, because fetch only rejects on network failure — HTTP 4xx and 5xx statuses resolve successfully.
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json(); POST with JSON
Send JSON data by setting the Content-Type header and stringifying the body. The fetch options object accepts method, headers, body, mode, credentials, cache, redirect, referrer, and integrity.
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', age: 30 })
}); AbortController
Cancel in-flight requests to prevent race conditions. Pass the signal to fetch, then call controller.abort() when the component unmounts or the user types a new query.
const controller = new AbortController();
fetch('/api/search', { signal: controller.signal })
.catch(err => {
if (err.name === 'AbortError') console.log('Cancelled');
});
controller.abort(); WebSocket
Open a persistent connection for real-time data. Unlike HTTP polling, WebSockets maintain an open channel with minimal overhead per message.
const ws = new WebSocket('wss://echo.websocket.org/');
ws.onopen = () => ws.send('Hello');
ws.onmessage = (e) => console.log('Received:', e.data);
ws.onclose = () => console.log('Disconnected'); Server-Sent Events
SSE provides one-way streaming from server to client over standard HTTP. It auto-reconnects, supports custom event types, and is simpler than WebSockets for push-only scenarios.
const source = new EventSource('/api/events');
source.onmessage = (e) => console.log('Event:', e.data);
source.addEventListener('price-update', (e) => {
console.log(JSON.parse(e.data));
}); Storage
Modern browsers offer multiple storage mechanisms with different characteristics. localStorage and sessionStorage provide simple key-value persistence with a ~5-10 MB limit. IndexedDB is an asynchronous, transactional object store capable of holding hundreds of megabytes. The Cache API stores Request/Response pairs, primarily for Service Worker offline strategies. Cookies travel with every HTTP request to the domain, making them suitable for authentication tokens but inefficient for large data.
localStorage and sessionStorage
Both APIs share the same interface but differ in lifespan. localStorage persists until explicitly cleared. sessionStorage is scoped to the tab and cleared when the tab closes. Values must be strings — serialize objects with JSON.stringify.
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
localStorage.removeItem('theme');
sessionStorage.setItem('tempToken', 'abc123');
// Cleared when tab closes Storage Events
The storage event fires in all other tabs/windows when localStorage or sessionStorage changes. It does NOT fire in the tab that made the change, making it ideal for cross-tab synchronization.
window.addEventListener('storage', (e) => {
console.log('Key changed:', e.key);
console.log('Old:', e.oldValue);
console.log('New:', e.newValue);
}); IndexedDB
IndexedDB is a low-level asynchronous database. You open a database, create object stores during upgrades, and perform transactions to add, get, put, delete, and cursor through records.
const request = indexedDB.open('MyAppDB', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const store = db.createObjectStore('users', {
keyPath: 'id', autoIncrement: true
});
store.createIndex('emailIndex', 'email', { unique: true });
};
request.onsuccess = (e) => {
const db = e.target.result;
const tx = db.transaction(['users'], 'readwrite');
const store = tx.objectStore('users');
store.add({ name: 'Alice', email: 'alice@example.com' });
}; Cache API
The Cache API stores HTTP responses for offline use. Open a named cache, add URLs, then match requests against cached responses in your Service Worker.
const cache = await caches.open('v1');
await cache.addAll(['/', '/styles.css', '/app.js']);
const response = await cache.match('/styles.css');
if (response) console.log('Served from cache'); Workers
JavaScript is single-threaded, but Web Workers run code on background threads without blocking the UI. Service Workers act as network proxies that intercept requests, manage caches, and enable offline experiences. Shared Workers can be accessed by multiple tabs from the same origin, making them useful for shared state or connection pooling.
Web Worker
Create a worker from a script file, send data with postMessage, and receive results via the onmessage handler.
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ numbers: [1, 2, 3, 4, 5] });
worker.onmessage = (e) => console.log('Sum:', e.data);
// worker.js
self.onmessage = (e) => {
const sum = e.data.numbers.reduce((a, b) => a + b, 0);
self.postMessage(sum);
}; Service Worker Registration
Register a Service Worker to enable offline capabilities, push notifications, and background sync. The scope controls which URLs the SW can intercept.
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js', { scope: '/' })
.then(reg => console.log('SW registered'))
.catch(err => console.error('SW failed', err));
} Service Worker — Fetch Intercept
The fetch event allows the Service Worker to serve cached responses when offline, or apply custom caching strategies like stale-while-revalidate.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
}); Observers
The Observer pattern APIs provide efficient, declarative ways to react to changes. IntersectionObserver detects when elements enter or leave the viewport — the foundation of lazy loading and infinite scroll. MutationObserver watches for DOM tree changes. ResizeObserver reacts to element size changes without polling. PerformanceObserver captures performance metrics like LCP and long tasks.
IntersectionObserver
Observe when an element crosses a visibility threshold. Much more efficient than scroll event listeners.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
}, { rootMargin: '200px' });
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img)); MutationObserver
Watch for DOM changes: added/removed nodes, attribute mutations, or character data changes.
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
console.log('Added:', mutation.addedNodes);
}
});
});
observer.observe(document.body, { childList: true, subtree: true }); ResizeObserver
React to changes in an element's content rectangle. More precise and efficient than window resize listeners.
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log(`Size: ${width}x${height}`);
}
});
observer.observe(document.querySelector('.container')); Media & Input
These APIs bridge the gap between web applications and hardware devices. getUserMedia accesses cameras and microphones. getDisplayMedia captures screen content. The Clipboard API reads from and writes to the system clipboard. The FileReader API processes user-selected files. Drag and Drop enables intuitive file upload and list reordering interfaces.
getUserMedia
Access the user's camera and microphone stream. Requires HTTPS and explicit user permission.
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: 1280, height: 720 },
audio: true
});
const video = document.querySelector('video');
video.srcObject = stream;
video.play(); Clipboard API
Copy and paste text programmatically. The modern navigator.clipboard API replaces the legacy document.execCommand('copy') approach.
// Write
await navigator.clipboard.writeText('Copied text');
// Read
const text = await navigator.clipboard.readText();
console.log(text); Drag and Drop
Implement file drop zones and list reordering. Remember to call preventDefault on dragover and drop events.
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
const files = e.dataTransfer.files;
console.log('Dropped:', files);
}); Utilities
These APIs solve common problems that every application faces. The URL and URLSearchParams constructors parse and build URLs safely. Blob and File create binary data client-side. FormData builds multipart bodies. The Web Crypto API provides encryption, hashing, and random number generation. The History API enables client-side routing. Geolocation retrieves the user's position. Notifications display system alerts. BroadcastChannel sends messages between tabs.
URL and URLSearchParams
Parsing URLs with string manipulation is error-prone. The URL constructor handles encoding, normalization, and provides convenient accessors for every component.
const url = new URL('https://example.com/path?foo=bar');
console.log(url.searchParams.get('foo')); // "bar"
url.searchParams.set('page', '2');
console.log(url.toString()); Web Crypto — Hash
Generate SHA-256 digests for data integrity. Always use crypto.subtle.digest instead of custom hashing for security-sensitive operations.
async function sha256(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
} Geolocation
Retrieve the user's geographic coordinates. watchPosition continuously monitors position changes; clearWatch stops monitoring.
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords.latitude, pos.coords.longitude),
(err) => console.error(err.message),
{ enableHighAccuracy: true, timeout: 5000 }
); The Interactive Cheat Sheet
Our free interactive Web APIs cheat sheet organizes eighty-five-plus API patterns into six categories with real-time search, category filtering, and one-click copy. Each entry includes a syntax-highlighted code example with color-coded keywords, API names, methods, strings, numbers, and comments.
The Satellite Uplink Station aesthetic uses deep space-black backgrounds, signal-green and transmission-blue accents, a subtle data-packet pulse animation with flying light trails, and precision telemetry typography. The design reinforces browser APIs as a communication system — each call a signal transmitted through the browser's internal network.
Everything is 100% client-side. Your API experiments and reference lookups never leave your browser.
Related Tools and References
Web APIs intersect with virtually every aspect of frontend and full-stack development. These related DevToolkit resources cover adjacent topics:
- JavaScript ES2024+ Features Cheat Sheet — 45+ modern APIs including Array Copying Methods, Iterator Helpers, Set Operations, and Promise Utilities.
- JavaScript Array Methods Cheat Sheet — 40+ methods with mutating vs non-mutating badges and ES2023 alternatives.
- JavaScript String Methods Cheat Sheet — 45+ methods across search, replace, split, trim, case conversion, and validation.
- JavaScript Error Handling Patterns Cheat Sheet — 45+ patterns covering try/catch, async/await, Promise errors, and global handlers.
- JavaScript Date/Time Methods Cheat Sheet — 45+ methods, patterns, and Temporal API preview.
- React Hooks Cheat Sheet — 20+ built-in hooks and 10 custom patterns.
- TypeScript Utility Types Cheat Sheet — 50+ utilities including Partial, Pick, Omit, Record, and deep utilities.
- Node.js Built-in Modules Cheat Sheet — 70+ APIs across File System, Network, Crypto, and Streams.
- CSS Animation Properties Cheat Sheet — 60+ entries covering @keyframes, transitions, transforms, and performance.
- HTTP Methods Cheat Sheet — All 9 HTTP/1.1 methods with RESTful design best practices.
Bookmark the Web APIs Cheat Sheet for instant access whenever you need to look up fetch options, IndexedDB transactions, Service Worker lifecycle events, or Web Crypto encryption patterns. Whether you are building a progressive web app, optimizing for offline use, or exploring the browser's capabilities, this reference provides the APIs and patterns you need.