Networking with fetch: Requests, Responses, Errors, Streaming, Uploads and Cancellation
Make HTTP requests with fetch: the two-step Response then body process, status and ok, headers, query parameters, JSON and form bodies, file uploads, streaming downloads with progress, CORS and credentials, AbortController and AbortSignal.timeout, request options and a reusable getJSON helper.
kvi5hnuCode Sprout team member8 min readOn this page
fetch() is the standard way to make HTTP requests from JavaScript. It's built into every browser, as well as Node, Deno and Bun, and it's promise-based, so it fits naturally with async/await (article 98). Its design has a few surprises, especially around errors, that cause real bugs. This article covers how it works step by step.
The runnable examples start a tiny local HTTP server with Node's http module, so they can make real requests without depending on the internet.
The two steps of a request
A fetch happens in two stages, with a promise for each:
await fetch(url)fulfills with aResponseas soon as the status line and headers arrive. The body may still be downloading.await response.json()(ortext(),blob(), ...) fulfills when the whole body has arrived and been parsed.

The most important rule is that HTTP error statuses don't reject. A 404 or 500 is a successful exchange of HTTP messages, so fetch fulfills with response.ok === false. It only rejects when no response arrives at all: the network is down, the host doesn't exist, CORS blocks the response, or the request is aborted. Always check response.ok (true for statuses 200–299) or response.status.
const http = require("node:http");
// A tiny local API so the example is self-contained
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname === "/api/teas") {
const q = url.searchParams.get("q") ?? "";
const teas = ["Green", "Black", "Oolong"].filter((t) => t.toLowerCase().includes(q.toLowerCase()));
res.writeHead(200, { "Content-Type": "application/json", "X-Total": String(teas.length) });
res.end(JSON.stringify(teas));
} else if (url.pathname === "/api/orders" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => { body += chunk; });
req.on("end", () => {
const order = JSON.parse(body);
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id: 42, ...order }));
});
} else if (url.pathname === "/slow") {
setTimeout(() => res.end("finally"), 2000);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
});
async function main() {
await new Promise((resolve) => server.listen(0, resolve));
const base = `http://localhost:${server.address().port}`;
// 1. GET with query parameters
const url = new URL("/api/teas", base);
url.searchParams.set("q", "o");
const response = await fetch(url);
console.log(response.status, response.ok, response.headers.get("content-type"));
console.log(response.headers.get("x-total"), await response.json());
// 2. A 404 is not a rejection
const missing = await fetch(`${base}/nope`);
console.log(missing.status, missing.ok, await missing.text());
// 3. POST JSON
const created = await fetch(`${base}/api/orders`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tea: "Oolong", grams: 100 }),
});
console.log(created.status, await created.json());
// 4. A body can only be read once
const once = await fetch(`${base}/api/teas`);
await once.text();
try {
await once.json();
} catch (err) {
console.log(once.bodyUsed, err.name);
}
// 5. Timeouts with AbortSignal.timeout
try {
await fetch(`${base}/slow`, { signal: AbortSignal.timeout(100) });
} catch (err) {
console.log(err.name);
}
// 6. Network failure: the promise rejects
try {
await fetch("http://localhost:1/");
} catch (err) {
console.log(err.name); // the message text differs between environments
}
server.closeAllConnections();
server.close();
}
main();
200 true application/json
1 [ 'Oolong' ]
404 false Not found
201 { id: 42, tea: 'Oolong', grams: 100 }
true TypeError
TimeoutError
TypeError
Each numbered part is explained below.
Responses: status, headers and body
A Response has:
status(200,404, ...),statusText,ok, and the finalurl(after redirects;redirectedtells you if any happened).headers, aHeadersobject withget(),has()and iteration. Header names are case-insensitive. For cross-origin responses, only a few "safe" headers are visible unless the server lists others inAccess-Control-Expose-Headers.- A body, read once with one of these methods, each returning a promise:
| Method | Result | Use for |
|---|---|---|
json() | parsed value | JSON APIs; rejects with SyntaxError for invalid JSON |
text() | string | HTML, CSV, plain text |
blob() | Blob | images and files: URL.createObjectURL(blob) makes a URL for <img src> |
arrayBuffer() / bytes() | ArrayBuffer / Uint8Array | binary formats (article 79) |
formData() | FormData | multipart responses (rare) |
After the body has been read, bodyUsed is true, and reading it again rejects with a TypeError (part 4 of the example). If you need the body twice, call response.clone() before reading.
Building requests
Query parameters
Build URLs with the URL and URLSearchParams classes (article 88), which encode values correctly, instead of concatenating strings. fetch accepts a URL object directly (part 1). Relative URLs such as "/api/teas" are resolved against the page's URL in browsers.
Method, headers and body
The second argument is an options object:
const response = await fetch("/api/orders", {
method: "POST", // GET is the default
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
body: JSON.stringify({ tea: "Oolong", grams: 100 }),
});
What the body can be, and the Content-Type that goes with it:
body value | Content-Type |
|---|---|
a string (often JSON.stringify(...)) | set it yourself, e.g. application/json |
URLSearchParams | application/x-www-form-urlencoded, set automatically |
FormData | multipart/form-data with a boundary, set automatically; don't set it yourself |
Blob / File | the blob's type |
ArrayBuffer, typed array | none; set it if the server needs one |
GET and HEAD requests can't have a body. Headers can also be given as a Headers object, and the URL and options can be packaged as a new Request(url, options) to pass to fetch.
Uploading files
A FormData object built from a form, or by hand, can include files from an <input type="file">:
const form = document.querySelector("#avatar-form");
const data = new FormData(form); // every named field, including files
data.append("uploadedAt", new Date().toISOString());
const response = await fetch("/api/avatar", { method: "POST", body: data });
fetch doesn't report upload progress in browsers. For a progress bar on large uploads, use XMLHttpRequest, whose upload.onprogress event provides it, or split the file into chunks.
Streaming the response body
response.body is a ReadableStream of Uint8Array chunks. Reading it chunk by chunk lets you show download progress, or process data, such as lines of a log or AI-generated text, before the whole response has arrived:
const http = require("node:http");
const lines = ["first line\n", "second line\n", "third line\n", "fourth line\n"];
const total = lines.join("").length;
const server = http.createServer(async (req, res) => {
res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": String(total) });
for (const line of lines) { // send the body in pieces, with pauses
res.write(line);
await new Promise((resolve) => setTimeout(resolve, 30));
}
res.end();
});
async function readWithProgress(response, onProgress) {
const expected = Number(response.headers.get("Content-Length")) || NaN;
const decoder = new TextDecoder();
let received = 0;
let text = "";
for await (const chunk of response.body) { // chunks are Uint8Arrays
received += chunk.length;
text += decoder.decode(chunk, { stream: true }); // handles characters split across chunks
onProgress(received, received / expected);
}
return text + decoder.decode();
}
async function main() {
await new Promise((resolve) => server.listen(0, resolve));
const response = await fetch(`http://localhost:${server.address().port}/log`);
const progress = [];
const text = await readWithProgress(response, (bytes, fraction) => progress.push(Math.round(fraction * 100)));
console.log(progress.at(-1), "% of", total, "bytes;", progress.length > 1 ? "several chunks" : "one chunk");
console.log(text.trim().split("\n"));
server.close();
}
main();
100 % of 46 bytes; several chunks
[ 'first line', 'second line', 'third line', 'fourth line' ]
TextDecoder with { stream: true } correctly handles multi-byte UTF-8 characters that are split between chunks. Content-Length may be missing (for example, for compressed or generated responses), in which case progress can only be shown as bytes received.
for await over a stream (article 99) works in Node and in current Chromium and Firefox. The version that works everywhere uses a reader:
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
handleChunk(value);
}
Streams can also be piped through transforms, like response.body.pipeThrough(new TextDecoderStream()) to get text chunks, or new DecompressionStream("gzip").
Cancelling and timeouts
Pass an AbortSignal as the signal option. AbortController lets you cancel on demand (when the user types a new search, or leaves the view), and AbortSignal.timeout(ms) creates a signal that aborts automatically:
let current;
async function search(term) {
current?.abort(); // cancel the previous, now outdated request
current = new AbortController();
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(term)}`, { signal: current.signal });
renderResults(await response.json());
} catch (err) {
if (err.name !== "AbortError") throw err; // an intentional cancel isn't an error
}
}
A user abort rejects with an AbortError. A timeout signal rejects with a TimeoutError (part 5). AbortSignal.any([a, b]) combines signals, so a request can respect both a caller's cancel signal and a timeout. The signal also aborts reading the body, not just waiting for headers.
A reusable helper
Most apps wrap fetch once, so that every call checks the status, applies a timeout and parses JSON in the same way:
class HttpError extends Error {
constructor(response, body) {
super(`HTTP ${response.status} for ${response.url}`);
this.name = "HttpError";
this.status = response.status;
this.body = body;
}
}
async function getJSON(url, { timeout = 8000, ...options } = {}) {
const signal = options.signal
? AbortSignal.any([options.signal, AbortSignal.timeout(timeout)])
: AbortSignal.timeout(timeout);
const response = await fetch(url, { ...options, signal, headers: { Accept: "application/json", ...options.headers } });
if (!response.ok) throw new HttpError(response, await response.text());
return response.status === 204 ? null : response.json();
}
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.url === "/ok") { res.writeHead(200, { "Content-Type": "application/json" }); res.end('{"teas":3}'); }
else if (req.url === "/empty") { res.writeHead(204); res.end(); }
else { res.writeHead(500); res.end("database unavailable"); }
});
async function main() {
await new Promise((resolve) => server.listen(0, resolve));
const base = `http://localhost:${server.address().port}`;
console.log(await getJSON(`${base}/ok`));
console.log(await getJSON(`${base}/empty`));
try {
await getJSON(`${base}/broken`);
} catch (err) {
console.log(err.name, err.status, err.body);
}
const controller = new AbortController();
controller.abort();
try {
await getJSON(`${base}/ok`, { signal: controller.signal });
} catch (err) {
console.log(err.name);
}
server.close();
}
main();
{ teas: 3 }
null
HttpError 500 database unavailable
AbortError
The custom error class keeps the status and the server's message, so callers can react differently to a 401 (log in again), a 404 (show "not found") and a 500 (retry later). A 204 No Content response has no body to parse.
CORS and credentials
Browsers apply the same-origin policy: a page can send requests to other origins, but it can only read the response if that server allows it with CORS headers such as Access-Control-Allow-Origin. If it doesn't, fetch rejects with a TypeError, and the details appear only in the developer console, deliberately hidden from scripts.
- "Simple" requests (GET, HEAD or POST with form-like content types and no custom headers) are sent directly.
- Others, such as a JSON POST, PUT, DELETE or a request with an
Authorizationheader, first trigger an automatic preflightOPTIONSrequest that asks the server for permission. - The
credentialsoption controls cookies:"same-origin"(the default) sends them only to your own origin,"include"sends them cross-origin too (the server must also opt in withAccess-Control-Allow-Credentials: true), and"omit"never sends them.
CORS is enforced by browsers to protect users. It doesn't apply in Node, which is why the same request can work in a script and fail in a page. The fix is always on the server, or in a proxy on your own origin.
Other request options
| Option | Purpose |
|---|---|
cache | "default", "no-store", "reload", "no-cache", "force-cache": how to use the HTTP cache |
mode | "cors" (default), "same-origin", "no-cors" (opaque responses you can't read) |
redirect | "follow" (default), "error" or "manual" |
referrerPolicy, referrer | what referrer information to send |
keepalive: true | lets a small request finish even if the page is closing, e.g. analytics on pagehide |
priority | "high", "low" or "auto": a hint for the browser's request scheduling |
integrity | the expected hash of the response, for subresource integrity |
For "fire and forget" analytics when a page closes, navigator.sendBeacon(url, data) is a simpler alternative to keepalive.
Common questions
Why didn't my catch block run when the server returned 500?
fetch only rejects for network-level failures. HTTP error statuses fulfill normally, so check if (!response.ok) throw ... yourself, or use a wrapper like getJSON.
Why does the same request work with curl or Node but fail in the browser?
Almost always CORS: the browser received the response but won't let the page read it, because the server didn't send the right Access-Control-Allow-* headers. Check the console's network panel, and fix the server's CORS configuration.
Should I still use XMLHttpRequest?
Only for upload progress events, or when maintaining old code. Everything else (streaming, cancellation, service workers, Node support) is better with fetch.
How do I retry failed requests?
Retry only network errors, timeouts and 5xx/429 responses, never 4xx client errors. Use exponential backoff with jitter (wait 0.5s, 1s, 2s... plus a random amount), respect a Retry-After header, and keep the number of attempts small.
Summary
fetchhas two steps: the promise for theResponsefulfills when headers arrive; body methods (json,text,blob,arrayBuffer) return a second promise.- HTTP errors don't reject. Check
response.ok. Only network failures, CORS blocks and aborts reject. - Send data with
method,headersandbody: JSON strings with a Content-Type,URLSearchParams, orFormData(with files) without one. - Stream
response.bodyfor progress and incremental processing; decode withTextDecoderusing{ stream: true }. - Cancel with
AbortController, add timeouts withAbortSignal.timeout(), and combine signals withAbortSignal.any(). - Cross-origin reads require CORS permission from the server;
credentialscontrols cookies.
Practice Questions
What does this log when the server responds with 404, and why?
try {
const r = await fetch("/missing");
console.log("got", r.status);
} catch {
console.log("failed");
}
Answer
got 404. A 404 is a valid HTTP response, so the promise fulfills. Only network-level failures reject.
Why does this upload fail on the server, and how do you fix it?
fetch("/upload", { method: "POST", headers: { "Content-Type": "multipart/form-data" }, body: formData });
Answer
Setting the Content-Type manually leaves out the boundary parameter that the server needs to split the multipart body. Remove the header and let fetch set it from the FormData.
How do you give a request a 5-second timeout while still letting the user cancel it with an AbortController named userCancel?
Answer
const signal = AbortSignal.any([userCancel.signal, AbortSignal.timeout(5000)]);
const response = await fetch(url, { signal });
You call response.json() and then response.text() on the same response. What happens?
Answer
The second call rejects with a TypeError, because the body stream has already been consumed (bodyUsed is true). Call response.clone() first if you really need to read the body twice.
Previous: Audio, Location and History: Web Audio, URLs, the History API and the Navigation API
Next: Server-Sent Events and WebSockets: Real-Time Updates in the Browser

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.