How to Use the JavaScript Fetch API With JSON and Timeouts
Copy-ready fetch() patterns for JSON requests, error handling, cancellation and CORS, with runnable examples and the request defaults MDN documents.
Checked against the official docs on Oct 24, 2026.

The JavaScript Fetch API sends HTTP requests with fetch(url, options) and gives you a promise for a Response. That promise only rejects on network-level failures, so you check response.ok yourself, then read the body once with a method like response.json(). Add an AbortSignal for timeouts and you have what most apps need.
The smallest fetch() call that works
Here's a complete GET request against a public, CORS-enabled API. Paste it into the console of any page:
const response = await fetch("https://api.github.com/repos/nodejs/node");
const repo = await response.json();
console.log(repo.full_name, repo.stargazers_count);There are two awaits because there are two separate waits. The first one settles as soon as the status line and headers arrive, which can happen before the body has finished downloading. The second one reads the body stream to the end and parses it as JSON.
fetch() takes a resource and an optional options object. The resource can be a URL string, anything with a stringifier such as a URL object, or a Request instance. Without options, the request is a plain GET. MDN's Using the Fetch API guide describes it as the modern, promise-based replacement for XMLHttpRequest, and the same global function exists in pages and in workers.
Why fetch() doesn't throw on 404 or 500
This is the mistake almost everyone makes once. A 404 or 500 is still a valid HTTP response, so fetch() fulfills with a Response and your catch block never runs. The promise rejects only for problems like a network error or a bad URL scheme. You have to look at the status yourself:
response.statusis the numeric code, such as200or404.response.okistruewhen the status is in the 200 range andfalseotherwise.response.statusTextis the reason phrase, likeNot Found.
The example below builds responses locally so you can see the behavior without a server. Response.json() creates a JSON response, and the data: URL at the end is fetched without touching the network. Save it as fetch-status.mjs and run node fetch-status.mjs:
async function readJson(response) {
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
return response.json();
}
const good = Response.json({ id: 7, name: "Ada" });
const missing = new Response("Not found", { status: 404, statusText: "Not Found" });
console.log("good.ok:", good.ok, "status:", good.status);
console.log("content-type:", good.headers.get("content-type"));
console.log("data:", await readJson(good));
console.log("missing.ok:", missing.ok, "status:", missing.status);
try {
await readJson(missing);
} catch (err) {
console.log("caught:", err.message);
}
const res = await fetch("data:application/json,%7B%22hello%22%3A%22world%22%7D");
console.log("data URL:", res.status, await res.json());Output in Node.js 24:
good.ok: true status: 200
content-type: application/json
data: { id: 7, name: 'Ada' }
missing.ok: false status: 404
caught: HTTP 404 Not Found
data URL: 200 { hello: 'world' }The missing response never throws on its own. Only the explicit !response.ok check turns it into an error your catch can handle. Put that check in one helper (there's a full one further down) instead of repeating it at every call site.
Sending JSON, forms and query strings
To send data, set method and body. You can't include a body with a GET request. For JSON, serialize the object and say what you're sending:
const response = await fetch("/api/tasks", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ title: "Write release notes", done: false }),
});
if (!response.ok) {
throw new Error(`Create failed: ${response.status}`);
}
const created = await response.json();
console.log("Created task", created.id);Forgetting JSON.stringify is a classic bug. Fetch converts any object it doesn't recognize into a string with its toString() method, so the server receives the literal text [object Object].
The body accepts more than strings: ArrayBuffer, typed arrays, DataView, Blob, File, URLSearchParams, FormData and ReadableStream. Two of those cover most forms:
// URL-encoded, like a classic HTML form post
await fetch("/login", {
method: "POST",
body: new URLSearchParams({ username: "ada", remember: "1" }),
});
// Multipart, for file uploads. Don't set Content-Type yourself:
// the browser adds it with the multipart boundary.
const form = document.querySelector("#avatar-form");
await fetch("/api/avatar", {
method: "POST",
body: new FormData(form),
});For GET requests, build the query string with URL and searchParams so every value gets encoded correctly:
const url = new URL("https://api.github.com/search/repositories");
url.searchParams.set("q", "fetch language:javascript");
url.searchParams.set("per_page", "5");
const response = await fetch(url);
const { items } = await response.json();
console.log(items.map((repo) => repo.full_name));Headers can be a plain object, as above, or a Headers instance you build with append() or set(). A Headers object lowercases header names, trims whitespace from values and refuses headers the browser controls itself, such as Host or Cookie. MDN calls those forbidden request headers. If a header you set never shows up in the Network panel, that's usually why.
Request bodies are streams, so one Request object with a body can only be sent once. If you need to retry it, call request.clone() before the first fetch().
Reading the response body
A Response gives you several ways to read its body. Each one returns a promise and reads the whole stream.
| Method | Resolves to | Use it for |
|---|---|---|
response.json() |
Parsed JavaScript value | JSON APIs |
response.text() |
String | HTML, CSV, plain text |
response.blob() |
Blob |
Images and files you'll show with URL.createObjectURL() |
response.arrayBuffer() |
ArrayBuffer |
Binary data you'll parse yourself |
response.bytes() |
Uint8Array |
Binary data as bytes, without wrapping an ArrayBuffer |
response.formData() |
FormData |
Multipart or URL-encoded responses |
response.body |
ReadableStream |
Large responses you want to process in chunks |
Each method throws if the body isn't in the format you asked for, so calling json() on an HTML error page fails with a parse error. Check response.headers.get("content-type") first when an API sometimes returns HTML.
The body can be consumed only once. After the first read, bodyUsed flips to true and any second read fails. If two parts of your code need the body, clone the response before reading it:
const res = Response.json({ items: [1, 2, 3] });
const copy = res.clone(); // clone BEFORE reading
console.log("bodyUsed before:", res.bodyUsed);
const data = await res.json();
console.log("parsed:", data, "bodyUsed after:", res.bodyUsed);
try {
await res.text(); // second read of the same body
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
console.log("clone still readable:", await copy.text());Output in Node.js 24:
bodyUsed before: false
parsed: { items: [ 1, 2, 3 ] } bodyUsed after: true
TypeError: Body is unusable: Body has already been read
clone still readable: {"items":[1,2,3]}The error is a TypeError everywhere, though the message text differs between browsers and Node.js.
For large text files, read response.body as a stream so you never hold the whole file in memory. TextDecoderStream turns the raw bytes into text:
const response = await fetch("/exports/orders.csv");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let chunks = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks += 1;
console.log(`chunk ${chunks}: ${value.length} characters`);
}Timeouts and cancellation
fetch() has no timeout option of its own. You cancel requests with an AbortSignal passed as the signal option, and there are three ways to get one:
new AbortController()gives you asignalplus anabort()method you call yourself, for example when the user clicks Cancel or types a new search term.AbortSignal.timeout(ms)returns a signal that aborts on its own after that many milliseconds. It aborts with aTimeoutErrorDOMException.AbortSignal.any([a, b])combines signals and aborts when any of them does, which is how you get "timeout or user cancel" on one request.
Because the error name tells you what happened, you can show a different message for each case. This example uses already-aborted signals and a data: URL, so it runs offline in Node.js as an .mjs file or in a browser console:
const url = "data:text/plain,hello";
async function tryFetch(label, signal) {
try {
const res = await fetch(url, { signal });
console.log(label, "->", await res.text());
} catch (err) {
console.log(label, "->", err.name);
}
}
await tryFetch("no signal", undefined);
const controller = new AbortController();
controller.abort();
await tryFetch("controller.abort()", controller.signal);
const timeout = AbortSignal.timeout(10);
await new Promise((resolve) => setTimeout(resolve, 50));
await tryFetch("AbortSignal.timeout(10)", timeout);
const either = AbortSignal.any([new AbortController().signal, timeout]);
await tryFetch("AbortSignal.any([...])", either);Output in Node.js 24:
no signal -> hello
controller.abort() -> AbortError
AbortSignal.timeout(10) -> TimeoutError
AbortSignal.any([...]) -> TimeoutErrorThe user-triggered abort and the timeout produce different names, which is exactly what the helper further down relies on.
A few details from MDN's AbortSignal.timeout() reference matter in practice. The timer counts active time, so it pauses while the page sits in the back-forward cache or a worker is suspended. There's no way to cancel the timer once it starts. And an abort that lands after fetch() resolved, but before you finished reading the body, makes the body read reject instead. As of October 2026, MDN marks AbortSignal.timeout() as Baseline widely available, with support across browsers since April 2024.
CORS, credentials and other request options
Every option fetch() accepts lives in the RequestInit object. These are the ones you'll reach for, with the defaults MDN's RequestInit reference documents:
| Option | Values | Default |
|---|---|---|
method |
Any HTTP method | GET |
mode |
cors, same-origin, no-cors, navigate |
cors |
credentials |
omit, same-origin, include |
same-origin |
cache |
default, no-store, reload, no-cache, force-cache, only-if-cached |
Not stated |
redirect |
follow, error, manual |
follow |
priority |
high, low, auto |
auto |
keepalive |
true, false |
false |
signal |
An AbortSignal |
None |
The mode and credentials rows cause most confusion.
Cross-origin requests and CORS
With the default cors mode, a request to another origin is sent, but the browser only hands the response to your code if the server answers with a matching Access-Control-Allow-Origin header. Requests that aren't "simple" (a JSON Content-Type, custom headers, methods like PUT) get a preflight first, and the real request isn't sent unless the preflight comes back with the right CORS headers. That's why a request can work in curl and fail in the browser: curl doesn't enforce CORS. The fix belongs on the server.
Switching to mode: "no-cors" doesn't fix it. You get an opaque response with status 0, no readable headers and a null body. MDN notes that most sites shouldn't use no-cors at all; its main use is in service workers.
Cookies and credentials
By default, fetch sends cookies, TLS client certificates and Authorization headers only on same-origin requests. To send them cross-origin, set credentials: "include". The server then has to reply with Access-Control-Allow-Credentials: true and name your exact origin in Access-Control-Allow-Origin, because a wildcard isn't allowed with credentials. Even then, cookies marked SameSite=Strict or SameSite=Lax aren't sent cross-site.
A reusable request helper
Real apps wrap fetch once so every call gets the same status check, timeout and error shape. This helper sends JSON when you pass json, merges your signal with a timeout, handles 204 No Content, and only parses JSON when the server says it's JSON:
export class HttpError extends Error {
constructor(response, body) {
super(`HTTP ${response.status} ${response.statusText} for ${response.url}`);
this.name = "HttpError";
this.status = response.status;
this.body = body;
}
}
export async function requestJson(url, { json, timeoutMs = 8000, signal, headers, ...init } = {}) {
const signals = [AbortSignal.timeout(timeoutMs)];
if (signal) signals.push(signal);
const response = await fetch(url, {
...init,
headers: {
Accept: "application/json",
...(json !== undefined && { "Content-Type": "application/json" }),
...headers,
},
body: json !== undefined ? JSON.stringify(json) : init.body,
signal: AbortSignal.any(signals),
});
if (response.status === 204) return null;
const type = response.headers.get("content-type") ?? "";
const body = type.includes("application/json")
? await response.json()
: await response.text();
if (!response.ok) throw new HttpError(response, body);
return body;
}Calling it, with one branch per failure type:
import { HttpError, requestJson } from "./request-json.js";
try {
const task = await requestJson("/api/tasks", {
method: "POST",
json: { title: "Write release notes", done: false },
timeoutMs: 5000,
});
console.log("Created", task.id);
} catch (err) {
if (err.name === "TimeoutError") {
console.error("The server took longer than 5 seconds");
} else if (err.name === "AbortError") {
console.error("The request was cancelled");
} else if (err instanceof HttpError) {
console.error(`Server said ${err.status}`, err.body);
} else {
console.error("Network or CORS failure", err);
}
}The error body is kept on HttpError, so validation messages from a 422 response reach your UI instead of disappearing.
Fetch in Node.js
Node.js ships the same API as globals: fetch, Request, Response, Headers and FormData. According to the Node.js globals documentation, fetch stopped needing the --experimental-fetch flag in v18.0.0 and was marked no longer experimental in v21.0.0. It's built on undici, and Node adds one extra option, dispatcher, for custom connection handling.
Two practical differences from the browser: there's no page origin, so pass absolute URLs instead of paths like /api/tasks, and there's no browser enforcing CORS on the response. Everything else covered above, including AbortSignal.timeout(), AbortSignal.any(), clone() and the body methods, works the same way, which is why the examples with printed output above run unchanged in Node.js 24.
Common fetch mistakes to check first
When a fetch call misbehaves, go through this list before anything else:
- Missing
awaitbeforeresponse.json(), so you log a pending promise instead of data. - No
response.okcheck, so a404HTML page reachesjson()and fails with a confusing parse error. - An object passed as
bodywithoutJSON.stringify, which sends[object Object]. - A hand-written
Content-Typeon aFormDataupload, which drops the multipart boundary. - Reading the same body twice instead of cloning it first.
- Using
no-corsto silence a CORS error, which leaves you with an unreadable opaque response.
If the console shows an error you can't place, the fix a bug from an error message prompt helps you work through it, and the web topic collects related browser guides.
Quick answers
Is fetch a replacement for XMLHttpRequest?
Yes. MDN calls the Fetch API the modern replacement for XMLHttpRequest: it's promise-based instead of callback-based and integrates with service workers and CORS.
Can I call fetch from a web worker or service worker?
Yes. fetch() is a global function in both window and worker contexts, so the same code runs in a dedicated worker or a service worker.
How do I send data when the user leaves the page?
Set keepalive: true in the fetch options. The browser then won't abort the request if the page unloads before it completes, but the body of a keepalive request is limited to 64 kibibytes.
Can I upload a ReadableStream with fetch?
Yes, ReadableStream is an accepted body type, but the options must then include duplex: "half", which means the browser sends the entire request before it processes the response.
Official sources
Next guide