Skip to content

Fetch API (Advanced)

In one line

The Fetch API is the modern interface for making HTTP requests, returning promises and supporting streams, abort, and credentials.

In simple words

The Fetch API is the modern replacement for XMLHttpRequest. It returns a Promise resolving to a Response object, integrates with the service worker cache, and supports request/response streaming, abort signals, and fine-grained control over credentials and headers.

A Request object encapsulates the method, URL, headers, body, and options like cache, credentials, mode, and redirect. The Response object exposes status, headers, and body-reading methods (text, json, blob, arrayBuffer, formData). The body is a ReadableStream, so you can process data in chunks — useful for large downloads or streaming JSON.

AbortController lets you cancel an in-flight request. You pass its signal to fetch and call controller.abort() to cancel. Combined with useEffect cleanup in React, this prevents state updates after unmount. The fetch API is the default for new code; use it over XHR or axios when possible.

Example

javascript
const controller = new AbortController();

async function fetchUser(id) {
  const res = await fetch(`/api/users/${id}`, {
    signal: controller.signal,
    headers: { "Accept": "application/json" },
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// Cancel the request if needed
// controller.abort();
fetchUser(1).then(console.log);

AbortController.signal is passed to fetch. Calling abort() cancels the request. res.ok checks the status; res.json() parses the body.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary