🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

The Fetch API: Errors, Aborts, and Streaming

Web FoundationsBrowser APIsđŸŸĸ Free Lesson

The Fetch API: Errors, Aborts, and Streaming

fetch replaced XMLHttpRequest because the old API was impossible to compose: callback pyramids for a simple GET, manual status checks, no streaming. fetch returns a promise for a Response object and gets the basic case down to one line. What it does not do — reject on HTTP error statuses, cancel itself, or protect you from reading a body twice — is where nearly every production bug lives.

This lesson treats fetch as a system rather than a one-liner: how errors actually surface, how AbortController makes cancellation first-class, how the Response body is a stream you get exactly one chance to read, and which of the request options you should be setting on every call rather than discovering during an incident.

The Body Is a Stream, Read Once

A Response wraps a readable stream. The helpers — json, text, blob, formData — each consume that stream and cache the result, so calling json twice on the same response is safe, but calling text and then json throws because the underlying bytes are gone. Clone the response before reading if you need both the parsed value and the raw stream, for example to log a payload while also returning it to application code.

This single-read rule is also why the service worker pattern of caching a response requires clone: two consumers, one body.

What fetch Actually Rejects On

fetch rejects its promise only when the request fails to complete at the network level — DNS failure, refused connection, offline mode, or an abort you triggered. A 404, a 500, or a 401 all resolve the promise with a Response whose ok property is false. Code that only attaches a catch handler will happily display "undefined" to the user when the API returns an error status:

javascript
async function getJSON(url, options) {
  let response;
  try {
    response = await fetch(url, options);
  } catch (networkError) {
    throw new ApiError('Network unreachable', { cause: networkError });
  }

  if (!response.ok) {
    let detail = null;
    try {
      detail = await response.json();
    } catch {
      /* error body was not JSON */
    }
    throw new ApiError(response.statusText || 'Request failed', {
      status: response.status,
      detail
    });
  }

  return response.json();
}

class ApiError extends Error {
  constructor(message, info = {}) {
    super(message);
    this.name = 'ApiError';
    this.status = info.status === undefined ? null : info.status;
    this.detail = info.detail === undefined ? null : info.detail;
    this.cause = info.cause === undefined ? null : info.cause;
  }
}

// Usage
try {
  const invoice = await getJSON('/api/invoices/42');
  renderInvoice(invoice);
} catch (error) {
  if (error instanceof ApiError && error.status === 401) {
    redirectToLogin();
  } else {
    showError(error.message);
  }
}

The wrapper has three deliberate branches: network failure becomes an ApiError with the original error attached as cause; a non-ok status reads the error body defensively, since error responses are not guaranteed to be JSON; and the caller can branch on status without string-matching messages. Centralizing this logic once — in a small api module, not in every component — is the difference between consistent error UX and forty slightly different handlers.

Aborting With AbortController

Every fetch accepts a signal tied to an AbortController. Calling abort rejects the in-flight promise with a DOMException named AbortError, closes the connection, and lets you stop work that no longer has a consumer — a search input whose user has already typed past the query, a page navigation that made an in-flight request moot:

javascript
const searchInput = document.getElementById('search');
let controller = null;

searchInput.addEventListener('input', async () => {
  if (controller) controller.abort();
  controller = new AbortController();

  const query = searchInput.value.trim();
  if (query.length < 2) {
    renderResults([]);
    return;
  }

  try {
    const results = await getJSON('/api/search?q=' + encodeURIComponent(query), {
      signal: controller.signal
    });
    renderResults(results);
  } catch (error) {
    if (error.name === 'AbortError') return;
    showError(error.message);
  }
});

Two details matter. AbortError must be swallowed silently — it is expected control flow, not a failure — so check the name before surfacing anything. And a single controller can be shared across multiple fetches, which is exactly what you want when one user action supersedes several pending requests at once. Timeouts are the same mechanism applied with setTimeout:

javascript
function withTimeout(ms, outerController) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  if (outerController) {
    outerController.signal.addEventListener('abort', () => controller.abort());
  }
  return { signal: controller.signal, done: () => clearTimeout(timer) };
}

POST, Headers, and Credentials

javascript
async function createOrder(payload, csrfToken) {
  const response = await fetch('/api/orders', {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrfToken
    },
    body: JSON.stringify(payload)
  });

  if (response.status === 201) {
    return response.json();
  }
  throw new ApiError('Order failed', { status: response.status });
}

The credentials option is the one most codebases get wrong by omission. The default sends cookies only for same-origin requests; same-origin is usually what you want for first-party APIs, while include is required when the API lives on another subdomain and must receive session cookies, and omit is the right choice for purely public endpoints and for requests whose cookies you refuse to leak. Pair cookie-based auth with a CSRF token on state-changing methods, because a cross-site form post will happily attach the user's cookies unless SameSite or the token stops it.

Streaming: Reading Before the Body Arrives

When a response is large — an export, a model download, a server-sent event stream — skip the one-shot helpers and consume the body reader directly:

javascript
async function streamToPage(url, onChunk) {
  const response = await fetch(url);
  if (!response.ok) throw new ApiError('Stream failed', { status: response.status });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let received = 0;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    received += value.byteLength;
    onChunk(decoder.decode(value, { stream: true }), received);
  }

  return received;
}

streamToPage('/api/export.csv', (text, total) => {
  console.log('Received', total, 'bytes so far');
});

The stream: true flag on the decoder is essential for multi-byte characters that straddle chunk boundaries — without it, an accented character at the edge of one chunk decodes as garbage. The same reader loop drives server-sent events you have chosen to handle manually, and progress bars for downloads, because response.ok still needs checking before you trust the stream.

Request Options That Deserve a Second Look

OptionValuesWhen it matters
cachedefault, no-store, reload, no-cache, force-cache, only-if-cachedAPI responses that must not come from the HTTP cache
credentialssame-origin, include, omitCookie behavior on cross-origin calls
redirectfollow, error, manualAPIs that must detect a 302 to a login page
referrerPolicyno-referrer, origin, strict-origin-when-cross-originAvoiding path leakage to third parties
keepalivetrue or falseSending beacons during page unload

cache: no-store is the correct setting for authenticated API GETs in most applications; without it, the shared HTTP cache can serve one user's response to another in edge cases involving proxy misconfiguration. keepalive: true lets a fetch survive the page that initiated it, which is how analytics beacons and form-submit unload handlers send their final payload.

Retries, Deduplication, and Reactivity

Automatic retries are tempting and dangerous: a GET that timed out is safe to retry, a POST that timed out may have already been applied server-side. If you add retry logic, restrict it to idempotent methods, cap the attempts, and use jittered backoff. Deduplicating concurrent identical GETs — one in-flight promise shared by every caller — removes a whole class of duplicate-render bugs in component-driven UIs. And remember that aborting is not just performance hygiene: in a UI where each keystroke triggers a request, without cancellation the responses can arrive out of order and the last-rendered result is whichever finished last, not whichever matched the input.

File uploads deserve one note of their own. When the body is a FormData instance, fetch sets the multipart content-type with its own boundary, and manually setting the Content-Type header to multipart/form-data without that boundary is the classic upload failure. Let the browser generate the header, or switch to a Blob with an explicit type when the endpoint expects raw bytes. Either way, watch upload progress with a ReadableStream body — fetch reports progress on the response side only, so streaming the request body through a TransformStream is the current approach for a real progress bar on large files.

Common Mistakes

Relying on catch alone to handle HTTP error statuses

Fix: Check response.ok and branch on response.status — only network failures reject the promise.

Swallowing AbortError into a user-visible error message

Fix: Check error.name for AbortError and return silently; aborts are expected control flow.

Reading a response body twice without cloning

Fix: Call response.clone() before a second read, or consume the stream once through helpers.

Retrying non-idempotent requests automatically

Fix: Retry GET and HEAD freely; require an idempotency key or manual confirmation for POST.

Forgetting credentials: include on cross-origin APIs

Fix: Set credentials explicitly and pair cookie auth with CSRF protection on mutations.

Key Takeaways

  • fetch rejects only on network-level failures — every HTTP status arrives as a resolved Response.
  • Centralize response.ok checks and status branching in one API wrapper.
  • AbortController cancels stale requests; treat AbortError as normal flow, not a failure.
  • The response body is a stream: one read, clone before a second consumer.
  • Set cache, credentials, and redirect deliberately on every API call instead of accepting defaults.
  • Stream large responses with getReader and TextDecoder, and guard retries by HTTP method.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement