Explain it simply
The Fetch API in plain language
fetch() is a built-in function that sends an HTTP request to a URL and returns a Promise that resolves to a Response object. It exists in every modern browser and has been a global in Node.js since version 18, so there is nothing to install.
It is like collecting a parcel at the post office. First the counter hands you the parcel, and you can read its label, the status and headers, straight away. The contents, the body, only come out when you unwrap it, which is awaiting response.json() or response.text(). The label might say 'undeliverable', so read it before you unwrap.
Problem → Why → Solution
The problem: an error page treated as data
The code below looks as if a missing user would land in the catch. In fact, when the server answers 404, fetch fulfils normally and { error: "Not Found" } is used as the user. user.name is undefined and the screen shows "Hello, undefined". If the server returns an HTML error page instead, json() fails with a SyntaxError that hides the real problem, an HTTP 500.
async function showUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json(); // also runs for 404 and 500
greet(`Hello, ${user.name}`); // "Hello, undefined"
} catch (error) {
showError(error); // only network failures and bad JSON get here
}
}Why fetch does not reject
To fetch, a 404 or 500 is a successful round trip: the server did answer. The Promise rejects only when no response arrives at all, such as a network failure, a CORS block or an abort. So you must check response.ok, which is true for statuses 200-299, before you read the body.
Core concept: one request, two Promises
fetch(url, options) works in two stages. The first await gives you a Response as soon as the response headers arrive: response.status (such as 200 or 404), response.ok (true for 200-299) and response.headers.get("content-type"). The body may still be downloading at this point. The second await, response.json(), waits for the whole body and parses it as JSON.
The body is a stream, so it can be read only once. Pick one of json(), text(), blob() or arrayBuffer(); calling text() after json() throws a TypeError because response.bodyUsed is already true. If you need the body twice, call response.clone() before reading. json() also rejects with a SyntaxError when the body is not valid JSON.
The options object shapes the request: method (GET by default), headers, body and signal. fetch does not turn objects into JSON for you, so you add body: JSON.stringify(data) and a "Content-Type": "application/json" header yourself. fetch has no built-in timeout either: create an AbortController, pass its signal, and call controller.abort() when time runs out. An aborted fetch rejects with an error whose name is "AbortError".
| Situation | What fetch does | How to detect it |
|---|---|---|
| 200 OK with JSON | fulfils | response.ok is true |
| 404 or 500 | fulfils | response.ok is false; read status |
| offline or CORS block | rejects with TypeError | catch block |
| abort or timeout | rejects with AbortError | check error.name |
In the browser, CORS and credentials matter too. When you call a different origin, JavaScript may read the response only if the server allows it with an Access-Control-Allow-Origin header. To send cookies with a cross-origin request, add credentials: "include".
Parsed JSON is still untrusted
A successful response.json() only proves the body was valid JSON syntax. It does not check that the fields you need exist or have the right types. Validate the shape of data from any API you do not control before using it; the JSON lesson goes deeper.
- await fetch gives a Response (headers)
- Check response.ok and status
- await response.json() gives data
- A body can be read only once
fetch's catch only covers 'no response came back'; 'the response was bad' is something you check yourself with response.ok.
General pattern
const response = await fetch(url, {
method: "POST", // default is "GET"
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload), // GET requests have no body
signal: controller.signal, // optional: allows abort
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json(); // read the body onceDescribe the request in the options object and await fetch. Check the status first, then await exactly one body-reading method.
Worked example: a getTodo that checks the status
Calling a real API from a lesson makes the output depend on the network, and code that never checks the status treats a 404 like a success. Here getTodo takes the fetch function as a parameter and checks response.ok: in production it uses the default fetch, and here it gets fakeFetch, which returns real Response objects, so it runs without a network and always prints the same output. id 1 prints the todo and id 999 prints the 404 error.
// A stand-in for the network. It returns real Response objects, so getTodo
// works unchanged with the real fetch in a browser or in Node 18+.
const todos = {
1: { userId: 1, id: 1, title: "delectus aut autem", completed: false },
};
async function fakeFetch(url) {
const id = Number(new URL(url).pathname.split("/").pop());
if (!todos[id]) {
return new Response(JSON.stringify({ error: "Not Found" }), { status: 404 });
}
return new Response(JSON.stringify(todos[id]), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
async function getTodo(id, fetchFn = fetch) {
const response = await fetchFn(`https://jsonplaceholder.typicode.com/todos/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} while loading todo ${id}`);
}
return response.json();
}
async function main() {
for (const id of [1, 999]) {
try {
const todo = await getTodo(id, fakeFetch);
console.log(todo);
} catch (error) {
console.log("Could not fetch data:", error.message);
}
}
}
main();Code breakdown
- Build a real Response
return new Response(JSON.stringify(todos[id]), {Response is the same class fetch returns. Given a body string, a status and headers, ok, status and json() behave exactly like a real response.
- Inject fetch
async function getTodo(id, fetchFn = fetch) {If no fetchFn is passed, the global fetch is used. Tests, and this lesson, pass fakeFetch instead, so no network is needed.
- Check before reading
if (!response.ok) {For the 404 response, fetch fulfilled but ok is false. Throwing our own Error here is what lets the caller's catch see the failure.
- Read the body
return response.json();Only a successful response gets its body parsed. Because this is a return inside an async function, the caller's await receives the parsed object.
- Handle each case
console.log("Could not fetch data:", error.message);For id 999 this prints the message getTodo threw. The loop continues, so one failing id does not affect the others.
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Could not fetch data: HTTP 404 while loading todo 999Sending data with POST
Sending data needs all three: the method, the header and a body that has been turned into a string. The echoServer below reports what it received and answers 201 Created using Response.json(). The output shows the method arrived as POST, the content type as application/json, and the body back as an object.
// The fake server echoes what it received, so we can see what fetch sent.
async function echoServer(url, options = {}) {
const received = {
method: options.method ?? "GET",
contentType: new Headers(options.headers).get("content-type"),
body: JSON.parse(options.body),
};
return Response.json({ id: 101, ...received }, { status: 201 });
}
async function createPost(post, fetchFn = fetch) {
const response = await fetchFn("https://api.example.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(post), // fetch does not serialise objects for you
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return { status: response.status, data: await response.json() };
}
createPost({ title: "Hello", draft: true }, echoServer).then(console.log);In real projects
fetch in real projects
Most projects do not call fetch directly in every component. A small helper such as getJson, or an api client module, keeps the status check, the timeout, JSON parsing and error-message mapping in one place, so a rule change is made once.
- The UI shows three states: loading, empty and error. A 404 might mean 'not found', a 500 'please try again later', and a timeout 'the connection is slow'.
- A search box aborts the previous request with AbortController whenever the user types again, so a slow old answer never overwrites a newer one.
- Because fetch is injected as a parameter, unit tests can cover 200, 404, 500 and offline cases with Response objects, exactly as this lesson does, without any network.
Common mistakes
Common mistakes with fetch
Skipping the response.ok check
fetch(...).then((r) => r.json()) treats 404 and 500 responses as successful data. You end up showing an error body as user data, or getting a confusing SyntaxError from an HTML error page. Always check if (!response.ok) before reading the body.
Passing an object straight into body
Writing body: { title: "Hi" } makes fetch send the string "[object Object]", which the server cannot parse. Use JSON.stringify(data) and add the Content-Type header as well.
Reading the body twice
Calling console.log(await response.text()) for debugging and then response.json() fails with a TypeError saying the body has already been read. Read text() once and call JSON.parse yourself, or use response.clone().
Assuming fetch has a timeout
fetch itself has no timeout option. If a server keeps the connection open without answering, your spinner can turn for a very long time. Give every request a time limit with an AbortController, or with AbortSignal.timeout(ms).
Best practices
Best practices
- Wrap fetch in one helper so the status check, timeout and error messages live in a single place.
- Show different messages for network errors, HTTP errors and invalid data, so users know what to do next.
- Inject the fetch function as a parameter and stub it with Response objects so the code is testable.
Mini challenge
Mini challenge: a getJson helper with a timeout
Write a getJson(url, { fetchFn, timeoutMs }) helper a whole project could use. The fake network offers five situations: good JSON, a 500, an HTML login page, being offline, and a slow server that never answers. Print one clear line for each.
- Use AbortController and setTimeout to abort after timeoutMs, and clear the timer in finally
- Turn an AbortError into "timed out after N ms" and other rejections into "network error: ..."
- Throw "HTTP <status>" when response.ok is false
- Throw "expected JSON, got <type>" when the content-type is not application/json
// Fake network: each path simulates a different real-world situation.
function fakeNetwork(url, { signal } = {}) {
const path = new URL(url).pathname;
if (path === "/slow") {
// never answers by itself; only the abort signal can end the wait
return new Promise((_, reject) => {
signal?.addEventListener("abort", () => reject(signal.reason));
});
}
if (path === "/offline") return Promise.reject(new TypeError("fetch failed"));
if (path === "/broken") {
return Promise.resolve(new Response("Internal error", { status: 500 }));
}
if (path === "/login-page") {
const headers = { "Content-Type": "text/html" };
return Promise.resolve(new Response("<h1>Please log in</h1>", { headers }));
}
return Promise.resolve(Response.json({ path, ok: true }));
}
async function getJson(url, { fetchFn = fetch, timeoutMs = 5000 } = {}) {
// TODO: create an AbortController and a timer that aborts after timeoutMs
// TODO: await fetchFn(url, { signal }) inside try/catch/finally
// TODO: map AbortError and other errors to clear messages; clear the timer
// TODO: check response.ok, then the content-type, then return the JSON
}
// TODO: call getJson for /users, /broken, /login-page, /offline and /slow
// with fetchFn: fakeNetwork and timeoutMs: 50, printing "<path> -> <result>"Expected: Five lines: /users -> { path: '/users', ok: true }, /broken -> HTTP 500, /login-page -> expected JSON, got text/html, /offline -> network error: fetch failed, /slow -> timed out after 50 ms.
Show hint
Aborting without a reason makes signal.reason a DOMException named "AbortError". Read the header as response.headers.get("content-type") ?? "" to cover a missing header.
Show solution
// Fake network: each path simulates a different real-world situation.
function fakeNetwork(url, { signal } = {}) {
const path = new URL(url).pathname;
if (path === "/slow") {
// never answers by itself; only the abort signal can end the wait
return new Promise((_, reject) => {
signal?.addEventListener("abort", () => reject(signal.reason));
});
}
if (path === "/offline") return Promise.reject(new TypeError("fetch failed"));
if (path === "/broken") {
return Promise.resolve(new Response("Internal error", { status: 500 }));
}
if (path === "/login-page") {
const headers = { "Content-Type": "text/html" };
return Promise.resolve(new Response("<h1>Please log in</h1>", { headers }));
}
return Promise.resolve(Response.json({ path, ok: true }));
}
async function getJson(url, { fetchFn = fetch, timeoutMs = 5000 } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
let response;
try {
response = await fetchFn(url, { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") throw new Error(`timed out after ${timeoutMs} ms`);
throw new Error(`network error: ${error.message}`);
} finally {
clearTimeout(timer);
}
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const type = response.headers.get("content-type") ?? "";
if (!type.includes("application/json")) throw new Error(`expected JSON, got ${type}`);
return response.json();
}
async function main() {
const paths = ["/users", "/broken", "/login-page", "/offline", "/slow"];
for (const path of paths) {
try {
const data = await getJson(`https://api.example.com${path}`, {
fetchFn: fakeNetwork,
timeoutMs: 50,
});
console.log(path, "->", data);
} catch (error) {
console.log(path, "->", error.message);
}
}
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- fetch fulfils with a Response once headers arrive and does not reject for 404 or 500; check response.ok yourself.
- A body can be read once, with one method such as json() or text().
- For POST, pass the method, a Content-Type header and a JSON.stringify body.
- Use AbortController for timeouts and cancellation, and inject fetch so code can be tested without a network.
MDN — Fetch API — MDN Web Docs