DOM & Browser APIs

Fetch & XHR

The fetch API is the modern way to make HTTP requests from the browser. It returns Promises, supports async/await, and handles JSON, files, and streaming. XHR is the legacy alternative — still needed for upload progress events.

How do you make an API request with fetch?

Call fetch(url), which returns a promise of a Response. Check response.ok, then read the body with await response.json() (or .text()). For POST requests, pass an options object with method, headers and a body, usually JSON.stringify(data). Cancel requests with an AbortController.

const res = await fetch("https://api.example.com/posts?limit=5");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();

await fetch("/api/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello" }),
});

const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });  ctrl.abort();

Fetch vs XHR

Promise-based✅ Yes❌ (callbacks)
async/await✅ Yes❌
Streaming✅ ReadableStream❌
Upload progress❌✅ xhr.upload.progress
Request cancellation✅ AbortController✅ xhr.abort()
HTTP error detection⚠️ Manual (check res.ok)⚠️ Manual
CORS✅ Full control✅ Full control

Response Body Methods

res.json()Parse body as JSON → Promise<any>
res.text()Read as UTF-8 string → Promise<string>
res.blob()Read as Blob (images, audio…)
res.arrayBuffer()Read as raw binary ArrayBuffer
res.formData()Read as FormData (service worker use)
res.bodyReadableStream for streaming reads

⚠️ A response body can only be consumed ONCE. Clone with res.clone() if you need to read it twice.

HTTP Methods Cheatsheet

GET
fetch('/api/users')
  .then(r => r.json())
POST
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' }),
})
PUT / PATCH
fetch('/api/users/42', {
  method: 'PUT',   // or 'PATCH'
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Bob' }),
})
DELETE
fetch('/api/users/42', { method: 'DELETE' })
  .then(r => r.ok || Promise.reject(r.status))

Common Pitfalls

fetch() only rejects on network failure — a 404 or 500 resolves successfully
Always check if (!res.ok) throw new Error(...) after every fetch call
Reading res.json() twice — the second call throws 'body already used'
Store the parsed value in a variable, or clone the response with res.clone() before reading
Leaving fetch requests running when a component unmounts — causes state updates on dead components
Use AbortController and call controller.abort() in the cleanup function of useEffect
Not setting Content-Type header for JSON POST — server receives garbled data
Always include headers: { 'Content-Type': 'application/json' } when sending JSON body

Interactive Fetch Demo

Code Editor

<button id="load">Load posts</button>
<ul id="posts"></ul>
<p id="err"></p>

Preview

Fetch API — step by step

1 / 4
1

fetch() returns a two-step Promise

fetch(url) resolves to a Response object as soon as the HTTP headers arrive — NOT after the body is downloaded. You then call response.json(), response.text(), or response.blob() to get another Promise that resolves when the body is fully received. This two-step model means you always need two awaits (or two .then() calls).

1 of 4
⚠️Always check response.ok
fetch resolves (does not throw) for any HTTP response, including 4xx and 5xx status codes. After awaiting fetch, always verify response.ok before calling response.json(). If you skip this check, a 500 error response body may be parsed as JSON and silently produce wrong data.

🎯 Quick Check

A fetch() call returns a Response with status 404. What happens?

Fetch API: summary

Key points

  • fetch rejects only on network errors; HTTP 404 and 500 still resolve, so check res.ok.
  • Requests to another domain must be allowed by that server's CORS headers.
  • Add credentials: "include" to send cookies cross-origin.
  • XMLHttpRequest is the older API; use fetch in new code.

Frequently asked questions

›Why am I getting a CORS error with fetch?

The server you're calling doesn't allow your origin. It has to send Access-Control-Allow-Origin; you can't fix this from the browser. Call it from your own backend instead.

›How do I set a timeout on fetch?

Pass signal: AbortSignal.timeout(5000) in the options.