TechEarl

The fetch() API: A Practical Guide

A practical guide to the fetch() API: the request/response model, why response.json() returns a promise, and the one surprise that bites everyone, fetch does not reject on 404 or 500. Plus headers, bodies, query strings with URLSearchParams, credentials, timeouts with AbortController, streaming NDJSON responses, and fetch in Node 18+.

Ishan KarunaratnePublished ⏱️ 24 min readUpdated
Share thisCopied
How to use JavaScript fetch(): why it doesn't reject on 404/500 (check response.ok), response.json(), timeouts with AbortSignal, and streaming bodies.

fetch(url, options) is the built-in way to make HTTP requests in JavaScript, in every current browser and in Node 18+. It returns a promise for a Response; you check response.ok, then read the body with await res.json(). This guide covers that model, bodies, headers, query string parameters with URLSearchParams, credentials, timeouts with AbortController, and streaming responses.

The single most important thing to know about fetch() is this: a 404 or a 500 is not an error as far as fetch is concerned. The promise still resolves. It only rejects when the request never completes at all, a dropped connection, DNS failure, CORS block. So this code, which looks completely reasonable, never treats a server error as an error:

javascript
// BROKEN: a 404 or a 500 status alone never reaches this catch
try {
  const res = await fetch("/api/user/42");
  const user = await res.json();   // tries to parse the error page
} catch (err) {
  console.error("request failed", err);
}

If the error page happens to be HTML, res.json() rejects with a SyntaxError and the catch does run, but for the wrong reason, with a misleading parse error. If the API returns a JSON error body, nothing throws at all and user silently holds the error payload.

You have to check response.ok yourself:

javascript
const res = await fetch("/api/user/42");
if (!res.ok) {
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const user = await res.json();

response.ok is true for any status in the 200–299 range and false otherwise. Get that one habit right and you have sidestepped the bug that fills the most "why isn't my fetch error handling working" threads. The rest of this guide is the request/response model around it.

The request/response model

fetch(url, options) returns a promise that resolves to a Response object as soon as the headers arrive. That is the part people miss: the promise settling does not mean the body has downloaded, it means the server has started replying. The body is read separately, and reading it is itself asynchronous.

javascript
const res = await fetch("https://api.example.com/widgets");
// res is a Response. The body has NOT been read yet.
res.status;      // 200
res.ok;          // true
res.headers.get("content-type");  // "application/json; charset=utf-8"

To get the body you call one of the Response body methods, and each of them returns a promise.

response.json() returns a promise, not your data

This is the second thing that trips people up. res.json() does not hand you the parsed object. It hands you a promise that resolves to the parsed object, because reading and parsing the body is async. You have to await it (or .then() it):

javascript
// WRONG: data is a Promise, not the object
const data = res.json();
console.log(data.name);   // undefined

// RIGHT
const data = await res.json();
console.log(data.name);   // "widget"

The full set of body readers, all promise-returning, each usable only once per response:

javascript
await res.json();         // parsed JSON
await res.text();         // raw string
await res.blob();         // Blob (images, files)
await res.arrayBuffer();  // ArrayBuffer (binary)
await res.formData();     // FormData

The "usable only once" part matters: the body is a stream, so calling res.json() after you already called res.text() throws body stream already read. If you need the raw text and the parsed object, read the text once and JSON.parse it yourself. (res.clone() exists for the rare case you genuinely need two independent reads.)

Putting the body gotcha together with the response.ok rule gives the canonical helper I reach for. Note the te_ prefix, it is just my own namespacing so the function does not collide:

javascript
async function te_getJSON(url, options) {
  const res = await fetch(url, options);
  if (!res.ok) {
    throw new Error(`HTTP ${res.status} on ${url}`);
  }
  return res.json();
}

const user = await te_getJSON("/api/user/42");

POST, PUT, and sending a body

The default method is GET. For anything else, pass an options object. To send JSON you set the method, the body (a string, so JSON.stringify your object), and a Content-Type header so the server knows how to parse it:

javascript
const res = await te_getJSON("/api/widgets", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "widget", price: 19 }),
});

body accepts more than strings: a FormData instance (for file uploads or multipart forms, do not set Content-Type yourself in that case, the browser sets the multipart boundary for you), URLSearchParams for form-encoded data, a Blob, or an ArrayBuffer. The method value is case-insensitive but conventionally uppercase.

Get and set query string parameters

A GET request carries its inputs in the query string, and the built-in parser for that is URLSearchParams. It has shipped in every browser since around 2017 and is a global in Node, so the same code reads ?page=2 in a click handler and in a request handler, no regex, no string splitting, no library:

javascript
const params = new URLSearchParams(window.location.search);
params.get("page");        // "2"  (or null if absent)

Read a parameter: get, getAll, has

For a URL like https://techearl.com/search?q=mysql&tag=db&tag=perf&page=2:

javascript
const params = new URLSearchParams(window.location.search);

params.get("q");        // "mysql"
params.get("missing");  // null   (not undefined, not "")
params.getAll("tag");   // ["db", "perf"]   every value for a repeated key
params.has("page");     // true
params.has("page", "2") // true   (second arg checks the value too)

get returns null when the parameter is absent, so a falsy check (if (!params.get("x"))) also fires on an empty ?x= value; use params.has("x") to tell "missing" from "present but empty." And get only ever returns the first value for a key. If a key can repeat (filters, tags, multi-select), you want getAll, which returns an array. That distinction is the most common bug I see with this API.

The constructor strips a leading ?, so new URLSearchParams("q=mysql&page=2") works too. For anything beyond the current page's own query string, parse the whole URL with new URL(...) and use its live searchParams: mutate it and url.href reflects the change, which is what you want when building a link to pass to fetch.

Set, append, and delete return undefined

set, append, and delete all mutate the object in place and return undefined. Do not write const next = params.set(...): next will be undefined.

javascript
const params = new URLSearchParams("tag=db&page=1");

params.set("page", "2");      // replaces: page is now "2". Returns undefined.
params.append("tag", "perf"); // adds another: tag is now ["db", "perf"]. Returns undefined.
params.delete("page");        // removes every "page". Returns undefined.

set replaces all existing values for the key with one; append adds another and keeps the rest. Use set for single-valued parameters (a page number, a sort order), append for repeated keys. delete with one argument removes every entry for that name; with a second argument it only removes entries matching that exact value.

URLSearchParams is also iterable: for (const [key, value] of params) yields one entry per value (repeated keys yield one entry each), and keys() and values() exist when you only need one side.

toString() has no leading question mark

javascript
const params = new URLSearchParams("a=1&b=2");
params.toString();   // "a=1&b=2"   NOT "?a=1&b=2"

const qs = params.toString();
const href = qs ? `/search?${qs}` : "/search";   // add the ? only if non-empty
const res = await fetch(href);

toString() is symmetrical with the constructor: the constructor strips a leading ?, toString() omits it. URL.search and location.search do include the ?, and mixing those two up is what produces ??a=1. The guard matters because toString() returns an empty string when there are no params, and you do not want a dangling /search?.

Update the URL without a reload

To reflect state into the address bar so it is bookmarkable, mutate a URL and hand it to the history API:

javascript
const url = new URL(window.location.href);
url.searchParams.set("page", "3");

history.replaceState(null, "", url);  // replace the current entry (no new back-button step)
history.pushState(null, "", url);     // or push a new entry (adds a back-button step)

Use replaceState for state that should not pollute the back button (a filter the user is tweaking live); use pushState when each change is a distinct "place" (a paginated view, a tab). Neither call reloads the page or fires popstate, so update any UI that depends on the query string yourself. For a "copy link" button after that, the Clipboard API (navigator.clipboard.writeText) against window.location.href is one call.

Object to query string, and the repeated-key trap

new URLSearchParams({ q: "mysql", page: "2" }) turns an object into q=mysql&page=2. Going back, Object.fromEntries(params) works for single-valued keys but keeps only the last value of a repeated key: ?tag=db&tag=perf becomes { tag: "perf" }, silently dropping db (see JavaScript object methods for why). When a key can repeat, build the shape with getAll:

javascript
const obj = {};
for (const key of new Set(params.keys())) {
  obj[key] = params.getAll(key);   // always an array
}
// { q: ["mysql"], tag: ["db", "perf"] }

Headers

You can pass headers as a plain object, as above, or build a Headers instance when you want to add to them programmatically:

javascript
const headers = new Headers();
headers.set("Authorization", `Bearer ${token}`);
headers.append("Accept", "application/json");

const res = await fetch("/api/me", { headers });

On the response side, res.headers is also a Headers object: res.headers.get("content-type"), res.headers.has("etag"), and it is iterable with for...of. Header names are case-insensitive, so get("Content-Type") and get("content-type") are the same.

Cookies and credentials

By default fetch sends cookies and HTTP auth on same-origin requests but not cross-origin ones. The credentials option controls this:

  • "same-origin" (the default): send credentials only to the same origin.
  • "include": send credentials even cross-origin. You need this for a cross-origin session-cookie API, and the server must answer with the matching CORS headers (Access-Control-Allow-Credentials: true and a specific origin, not *).
  • "omit": never send credentials.
javascript
const res = await fetch("https://api.example.com/me", {
  credentials: "include",
});

fetch is global in Node now, so node-fetch is done

If you searched for node-fetch, you almost certainly do not need it anymore. fetch has been a global in Node since v18 (April 2022), no import, no flag to enable it, and it was marked stable in Node 21. The same fetch, Response, Headers, and Request you use in the browser are there in Node:

javascript
// Node 18+, no require, no import, no node-fetch
const res = await fetch("https://api.github.com/repos/nodejs/node");
const repo = await res.json();
console.log(repo.stargazers_count);

node-fetch still has a narrow place, supporting a pre-18 runtime, or a CommonJS codebase wanting a particular API shape, but for new code on a current Node, reaching for it is a reflex worth dropping.

The limitations worth knowing up front

Two gaps catch people, and both have a real answer rather than a workaround.

No built-in timeout. fetch will wait as long as the browser or runtime allows; there is no timeout option. A hung server hangs your request. The right tool is AbortController/AbortSignal, and the modern one-liner is AbortSignal.timeout(ms). The full pattern, including combining a timeout with a manual cancel, is in add a timeout to fetch below.

No upload progress. fetch cannot report upload progress, there is no onprogress event. If you need a progress bar for a file upload, XMLHttpRequest (via its upload.onprogress) is still the only API that gives it to you directly. For download progress you can read the response body as a stream and count bytes as they arrive, which is also how you consume NDJSON or streaming LLM responses, see stream a fetch response below.

Add a timeout to fetch

fetch() has no timeout option, so by default a request can hang for as long as the OS lets the socket stay open. The modern fix is one extra option:

javascript
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
const data = await res.json();

AbortSignal.timeout(5000) returns a signal that aborts itself after 5000 milliseconds. Pass it as signal and the fetch is cancelled the moment the timer fires. No manual setTimeout, no flag to track, no cleanup. That is the whole answer for the common case; the subsections below cover cancelling by hand, combining a timeout with a user cancel, telling a timeout apart from a real network error, and the one thing abort does not do.

Why the old setTimeout race did not work

For years the standard advice was to race the fetch against a timer:

javascript
// DON'T: this does not cancel anything
function te_fetchTimeout(url, ms) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error("timeout")), ms)
    ),
  ]);
}

This rejects after ms, so your code moves on. But the fetch itself is still running. The connection stays open, the bytes keep arriving, and any work the request kicked off keeps going. You did not add a timeout; you added a way to ignore a request that is still consuming a socket. Promises do not model cancellation, which is exactly why AbortController exists as a separate primitive. If you have this pattern in a codebase, it is the thing to replace.

Cancel a fetch with AbortController

AbortSignal.timeout() is perfect when time is the only trigger. When you also need to cancel on a button click, a route change, or because a newer request superseded this one, reach for AbortController directly:

javascript
async function teLoadWithCancel(url, cancelButton) {
  const controller = new AbortController();

  // Cancel on demand:
  cancelButton.addEventListener("click", () => controller.abort(), { once: true });

  // And still time out:
  const timer = setTimeout(() => controller.abort(), 5000);

  try {
    const res = await fetch(url, { signal: controller.signal });
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}

One controller, one signal, two ways to trip it. The clearTimeout in finally matters: once the fetch settles, you do not want a stray timer firing abort() on a controller nobody is listening to anymore. finally runs whether the request succeeded, failed, or was aborted, which makes it the right place for that cleanup.

Combine a timeout and a user cancel with AbortSignal.any

The hand-rolled controller above mixes two concerns into one object. Since 2023 there is a cleaner way to express "abort if either of these fires": AbortSignal.any() takes an array of signals and returns a single signal that aborts as soon as any one of them does.

javascript
function te_fetchWithCancel(url, userSignal, ms = 5000) {
  const signal = AbortSignal.any([userSignal, AbortSignal.timeout(ms)]);
  return fetch(url, { signal });
}

// caller keeps its own controller for the manual cancel:
const controller = new AbortController();
const url = "https://api.github.com/repos/nodejs/node";
const data = await te_fetchWithCancel(url, controller.signal).then((r) => r.json());
// ...later: controller.abort();

Now the timeout and the user cancel are independent, composable signals. You can pass userSignal down through several layers (a React component's cleanup signal, a request-scoped signal from a framework) and combine it with a fresh timeout at the call site, without anyone needing to know about the others.

Catch AbortError and TimeoutError, not real errors

An aborted fetch rejects with a DOMException whose name is "AbortError". By spec, a timeout via AbortSignal.timeout() rejects with name === "TimeoutError", and Firefox, Node (undici) and Chrome/Edge 124+ do exactly that. Older Chromium (Chrome and Edge 103 to 123) surfaced the timeout as an AbortError instead, so on those versions a catch that only matches TimeoutError falls through to the generic branch. If you still support them, the robust split handles both names as "did not finish" and re-throws everything else (DNS failure, connection refused, TLS error):

javascript
async function teFetchWithTimeout(url) {
  try {
    const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (e) {
    if (e.name === "TimeoutError" || e.name === "AbortError") {
      // request did not finish: our timeout fired, or someone cancelled.
      // Chromium before 124 reported a timeout as AbortError, so handle both.
      console.warn("Request timed out or was cancelled");
      return null;
    }
    throw e; // real failure: network down, bad TLS, server unreachable
  }
}

If you genuinely need to separate "timed out, retry?" from "you cancelled this" and cannot trust the name across engines, track your own intent: keep the timeout's AbortController and your user-cancel AbortController separate, and in the catch read which signal aborted (signal.aborted / signal.reason) rather than the error name. Note the if (!res.ok) throw line too: a timeout wrapper alone will happily resolve a 404 or 500, for the reason at the top of this page.

Abort is client-side

Aborting a fetch closes the connection from your side. Whether the server stops the work it already started is entirely up to the backend. If your fetch triggered a payment, a database write, or a long report generation, calling abort() does not roll any of that back; the request may have already reached the server and committed before the abort landed. Make the operation idempotent, or have the server honour a cancellation token of its own. The client-side abort is about not waiting and not leaking a socket, not about undoing server effects.

AbortSignal support in browsers and Node

None of this is browser-only. Node has had AbortSignal.timeout() since 17.3 and global fetch since 18, so the exact same one-option timeout works server-side with no node-fetch dependency, and the same helper runs in a browser bundle and a Node API route unchanged. For the delay side of a retry loop, see sleep, wait, and poll in JavaScript.

FeatureBrowserNode.jsNotes
AbortController / signalChrome 66Node 14.17The base primitive; widely available.
AbortSignal.timeout()Chrome 124Node 17.3 (backported to 16.14), stable in 18The one-line timeout. The static method landed in Chrome 103, but MDN counts full support from 124 (Chromium did not surface TimeoutError correctly with fetch before then).
AbortSignal.any()Chrome 116Node 20.3 (2023)Combine multiple signals.

AbortController and the signal option are universal now. If you must support a runtime older than Chrome 103 / Node 17.3, fall back to the manual AbortController + setTimeout form above (it goes back to Chrome 66 / Node 14.17). AbortSignal.any() is the newest of the three, so guard it with a typeof AbortSignal.any === "function" check if you target older environments.

Stream a fetch response

await response.json() waits for the whole body to arrive before you get a single byte. If the server is streaming (a long list of records, server-sent events, an LLM emitting tokens), you want to read the body as it lands. response.body is a ReadableStream, and the modern way to consume it is to async-iterate it:

javascript
const response = await fetch("/api/events");

for await (const chunk of response.body) {
  // chunk is a Uint8Array of raw bytes, as they arrive over the wire
  console.log(chunk.length, "bytes");
}

Check response.ok before the loop, exactly as above, or you will happily stream an error page. Reading the body as a stream is also how you get download progress: count the bytes as the chunks arrive.

Decode the bytes with TextDecoderStream

The chunks are Uint8Array byte buffers, and a multi-byte UTF-8 character can be split across two chunks. Do not decode each chunk in isolation with new TextDecoder().decode(chunk): a chunk boundary landing mid-character gives you mojibake. TextDecoderStream is stateful and carries a partial character over to the next chunk, so pipe the byte stream through it and iterate the text instead:

javascript
const response = await fetch("/api/events");
const textStream = response.body.pipeThrough(new TextDecoderStream());

for await (const text of textStream) {
  // text is a string, correctly decoded across chunk boundaries
  process.stdout.write(text);
}

pipeThrough returns the readable side of the transform, so you can keep chaining.

Split a stream into NDJSON lines

NDJSON (newline-delimited JSON) is one JSON object per line, the standard shape for streaming APIs because each line is independently parseable the moment its trailing newline arrives. The catch: stream chunks do not align to line boundaries. One chunk might hold two and a half lines, and the half-line has to wait for the next chunk. A small TransformStream handles it with no library: it buffers text, emits whole lines, and holds the remainder.

javascript
function teLineSplitter() {
  let buffer = "";
  return new TransformStream({
    transform(chunk, controller) {
      buffer += chunk;
      const lines = buffer.split("\n");
      buffer = lines.pop(); // last element is the incomplete trailing line
      for (const line of lines) {
        if (line) controller.enqueue(line);
      }
    },
    flush(controller) {
      // emit whatever is left when the stream ends (no trailing newline)
      if (buffer) controller.enqueue(buffer);
    },
  });
}

Chain it after the decoder and parse each line as it pops out:

javascript
const response = await fetch("/api/records");
if (!response.ok) throw new Error(`HTTP ${response.status}`);

const lines = response.body
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(teLineSplitter());

for await (const line of lines) {
  const record = JSON.parse(line);
  handle(record); // runs per record, as it arrives, not after the whole response
}

The first record is in your hands the moment the first newline lands, regardless of how many thousands follow. Memory stays flat because you never hold the full body, only one line plus the current buffer tail.

Read SSE and streaming LLM responses

This pattern is the foundation of every streaming chat UI. Server-sent events and the OpenAI/Anthropic-style token streams are both line-oriented text over a single long-lived fetch response: SSE frames are blank-line-separated blocks of data: lines, and an LLM token stream is usually NDJSON or SSE where each frame carries the next token. The splitter above gets you most of the way to consuming a model response by hand, without the SDK:

javascript
const response = await fetch("https://api.example.com/v1/chat", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ model: "...", stream: true, messages }),
});

const lines = response.body
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(teLineSplitter());

for await (const line of lines) {
  if (!line.startsWith("data: ")) continue;
  const payload = line.slice(6);
  if (payload === "[DONE]") break;
  const { delta } = JSON.parse(payload);
  if (delta) appendToken(delta); // paint the token the instant it arrives
}

The difference between this and await response.json() is the difference between a chat box that types as the model thinks and one that sits blank for ten seconds and then dumps a wall of text. Same network call, different consumption.

Backpressure comes for free. for await...of only pulls the next chunk when your loop body returns, so a slow consumer (writing each record to a database, painting to the DOM) naturally throttles the producer, and with piped transforms that backpressure propagates all the way up the chain to the network read. You never buffer the whole body while a slow handler falls behind, and you write no flow-control code to get that.

The getReader() fallback

Async iteration over response.body is the newest piece here, and support landed unevenly: Firefox 110 (2023) first, Chrome and Edge 124 (April 2024), Node.js since 18, and Safari only in 26.4. On older targets the stream is there but the for await...of shortcut is not, so drop to the reader API, which works everywhere ReadableStream does:

javascript
const reader = response.body
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(teLineSplitter())
  .getReader();

try {
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    handle(JSON.parse(value));
  }
} catch (err) {
  await reader.cancel(err); // stop the download if handling fails part way
  throw err;
} finally {
  reader.releaseLock();
}

read() returns { value, done } and you loop until done. The two cleanup calls do different jobs: cancel() tells the stream you want nothing more, so the rest of the response is not downloaded, while releaseLock() only frees the stream for another reader and leaves the download running. When you stop early and do not want the remainder, cancel first, then release the lock. The async-iterator form does both for you: leaving a for await...of loop early through break, return or a throw cancels the stream by default, which is why it is the default once your targets support it.

FeatureChrome / EdgeFirefoxSafariNode.jsNotes
response.body as ReadableStream436510.118 (global fetch)The stream itself; read via getReader() everywhere.
TextDecoderStream7110516.418Cross-browser baseline since Sep 2022.
TransformStream6710214.118Web Streams in Node since 18.
Async iteration (for await...of on response.body)12411026.418Newest; getReader() is the fallback below these.

TextDecoderStream, TransformStream, and global fetch all landed in Node.js 18, so the entire NDJSON pipeline runs unchanged server-side.

When does fetch actually reject?

Closing the loop on where we started. The promise fetch returns rejects in a small set of cases, all of them "the request never produced an HTTP response":

  • A network failure (offline, connection dropped, DNS resolution failed).
  • A CORS policy block (you get a TypeError, deliberately opaque so the page cannot probe cross-origin responses).
  • The request was aborted via an AbortController (rejects with an AbortError).
  • A malformed URL or a few other request-construction errors.

Everything else, every status code the server actually sent back, is a successful fetch with a Response you must inspect. That is the whole reason response.ok exists, and the whole reason this guide leads with it.

FAQ

No. This is the most common fetch surprise. The promise resolves normally for any HTTP response, including 404 and 500; only a network-level failure (dropped connection, DNS error, CORS block, abort) causes a rejection. You must check response.ok (true for 200–299) or response.status yourself and throw if the request failed.

Because reading and parsing the response body is asynchronous, res.json() returns a promise that resolves to the parsed object, not the object itself. Await it: const data = await res.json();. The same is true of res.text(), res.blob(), and the other body readers.

No. The body is a one-shot stream, so calling res.json() after res.text() (or calling either twice) throws "body stream already read." If you need it twice, read it once and reuse the value, or call res.clone() before the first read to get an independent copy.

For new code on a current Node, no. fetch has been a global since Node 18 (no import, no flag) and is stable as of Node 21. node-fetch only earns its place on a pre-18 runtime or a CommonJS codebase that wants its specific API shape.

There is no built-in timeout option. Pass an AbortSignal: the modern one-liner is fetch(url, { signal: AbortSignal.timeout(5000) }), which aborts the request after 5 seconds and rejects with a TimeoutError (a manual controller.abort() gives an AbortError instead). It works the same in Node 18+. See add a timeout to fetch for the full pattern.

Create an AbortController, pass controller.signal to fetch, and call controller.abort() in the click handler. Use this when the trigger is a user action rather than time. You can also feed both a user signal and AbortSignal.timeout(ms) into AbortSignal.any([...]) to cancel on either.

Check the error's name in your catch block. By spec a timeout from AbortSignal.timeout() rejects with name === "TimeoutError" and a manual abort() gives name === "AbortError"; a real failure (DNS, connection refused, TLS) is neither, so re-throw it. One caveat: Chrome and Edge before version 124 reported a fetch timeout as AbortError, not TimeoutError, so match both names for the not-finished case if you support those versions.

No. Abort closes the connection on the client side. Whether the server stops mid-work is backend-dependent, and the request may have already committed (a write, a charge) before the abort arrived. Make the operation idempotent or have the server honour its own cancellation if undoing the effect matters.

response.json() buffers the entire body, then parses it. You get nothing until the last byte arrives, and the whole payload sits in memory. Streaming reads the body as it lands, so the first record is usable immediately and memory stays flat. Use .json() for small, bounded responses; stream for long lists, SSE, and token streams.

A single UTF-8 character can be split across two byte chunks. Calling new TextDecoder().decode(chunk) on each chunk in isolation corrupts any character that straddles a boundary. TextDecoderStream is stateful: it holds the partial character and finishes it on the next chunk, so multi-byte text decodes correctly.

Use response.body.getReader() and loop on await reader.read() until done is true, then call reader.releaseLock() (call reader.cancel() first if you stop before the end and do not want the rest of the body). Async iteration over ReadableStream arrived in Firefox 110, Chrome 124, Node 18, and only reached Safari in 26.4, so the reader API is the portable fallback for older Safari and anything before those versions.

By design. toString() returns just the parameter pairs ("a=1&b=2") so it is symmetrical with the constructor, which strips a leading ?. Only URL.search and location.search include the ?. When you stitch a URL by hand, add the ? yourself, and only when the string is non-empty.

Use getAll, which returns an array of every value for the key: params.getAll("tag") on ?tag=db&tag=perf returns ["db", "perf"]. Plain get only returns the first, and Object.fromEntries(params) keeps only the last, so neither is safe for repeated keys.

By default fetch sends credentials on same-origin requests only. For a cross-origin API that relies on a session cookie, set credentials: "include", and the server must respond with Access-Control-Allow-Credentials: true and a specific allowed origin (not *). Use credentials: "omit" to never send them.

See also

Sources

Authoritative references this article was fact-checked against.

Tagsfetchfetch apijavascripthttpnode.jsAbortControllerfetch timeoutReadableStreamURLSearchParamsquery string

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts