What is the Fetch API?

The Fetch API is the built-in, promise-based way to make HTTP requests in browsers, Node.js (18+), Deno, Bun and edge runtimes: fetch(url, options) returns a promise of a Response.

Basic flow

  1. const res = await fetch(url, options).
  2. Check res.ok (status 200-299) or res.status.
  3. Read the body once with res.json(), res.text(), res.blob(), res.arrayBuffer() or res.formData().

The surprise: HTTP errors do not reject

fetch rejects only on network failures (offline, DNS, CORS blocked, aborted). A 404 or 500 fulfills normally. Always check res.ok and throw yourself.

Common options

  • method: "POST", "PUT", "DELETE"...
  • headers: e.g. { "Content-Type": "application/json", Authorization: "Bearer ..." }
  • body: a string (JSON.stringify(data)), FormData, Blob or URLSearchParams. With FormData, do not set Content-Type yourself; the browser adds the multipart boundary.
  • signal: an AbortSignal to cancel, e.g. AbortSignal.timeout(5000).
  • credentials: "include" to send cookies cross-origin.
  • cache: control the HTTP cache. In Next.js, fetch also accepts next: { revalidate, tags }.

Good habits

  • Wrap fetch in a small helper that checks ok, parses JSON and throws a meaningful error.
  • Cancel requests that are no longer needed (component unmount, a new search) with AbortController.
  • A body can be read only once; use res.clone() if you need it twice.

Code example

js
1// A small fetch wrapper with timeout and proper HTTP error handling
2async function fetchJson(url, { timeout = 5000, ...options } = {}) {
3 const res = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });
4 if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
5 return res.json();
6}
7
8// data: URLs let this example run offline; real code would call an API URL
9const todo = await fetchJson('data:application/json,{"id":1,"title":"Learn fetch","done":false}');
10console.log(todo.title, todo.done); // Learn fetch false
11
12// POST JSON (shape of a real request)
13const request = new Request("https://api.example.com/todos", {
14 method: "POST",
15 headers: { "Content-Type": "application/json" },
16 body: JSON.stringify({ title: "Write tests" }),
17});
18console.log(request.method, request.headers.get("Content-Type")); // POST application/json
19
20// Cancel a request that's no longer needed
21const controller = new AbortController();
22const pending = fetch("data:text/plain,hello", { signal: controller.signal });
23controller.abort();
24try {
25 await pending;
26} catch (e) {
27 console.log(e.name); // AbortError
28}
29
30// Reading the body: text, json, blob...
31const res = await fetch("data:text/plain,plain text body");
32console.log(res.ok, res.status, await res.text()); // true 200 plain text body

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app