Lesson 9 of 12 · 11 min · Asynchronous JavaScript
fetch: calling APIs from JavaScript
What you will learn
- Make GET and POST requests with
fetch - Read the response status, headers and body as JSON or text
- Handle HTTP errors correctly (
response.ok) - Send headers, JSON bodies, forms and files
- Cancel requests, handle timeouts and build a small API helper
In simple words
fetch is how a web page asks a server for data or sends data to it without reloading: loading a list of courses, saving a form, checking a username. You call fetch with an address, it gives back a promise, and when the answer arrives you read the data from it. The one surprising rule: fetch only fails when the network fails; a "404 not found" still counts as an answer, so you have to check for it yourself.
Words to know
- Request and response: what the browser sends to a server and what comes back.
- Status code: a number such as 200 (OK) or 404 (not found) in the response.
- JSON: the text format most APIs use for data.
- AbortController: an object that lets you cancel a request that is in progress.
A simple GET
const response = await fetch("https://api.example.com/courses");
const courses = await response.json(); // parse the body as JSON (also returns a promise)
console.log(courses.length);
fetch returns a promise for a Response as soon as the headers arrive; the body is read separately, and also asynchronously. Body readers (each can be used once): response.json(), response.text(), response.blob(), response.arrayBuffer(), response.formData(), or response.body as a stream. Use response.clone() if you need to read it twice.
fetch does not reject on HTTP errors
const response = await fetch("/api/orders/9999"); // the server answers 404
console.log(response.ok); // false
console.log(response.status); // 404
The promise rejects only on network failures (offline, DNS failure, blocked by CORS, aborted). A 404 or 500 still fulfils the promise. So always check:
async function getJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new Error(`HTTP ${response.status} ${response.statusText}: ${detail}`);
}
return response.json();
}
response.ok is true for status 200 to 299. Read response.status for finer decisions (401: send to login; 404: show not found; 429: wait and retry; 5xx: show an error). Many APIs return a JSON error body (for example RFC 9457 problem details), which you can parse with await response.json() for the message.
POST, PUT and DELETE
const response = await fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
},
body: JSON.stringify({ customerId: 3, productIds: [1, 2] }),
});
if (response.status === 201) {
const created = await response.json();
const location = response.headers.get("Location"); // e.g. /api/orders/101
}
await fetch(`/api/orders/${id}`, { method: "DELETE" }); // 204 No Content has no body to read
- Set
Content-Type: application/jsonwhen sending JSON; the body must be a string (JSON.stringify). - The options:
method,headers,body,mode(cors,same-origin,no-cors),credentials,cache,redirect,signal,keepalive. - Build query strings with
URLSearchParamsrather than gluing text:
const params = new URLSearchParams({ status: "paid", page: 2, q: "java & spring" });
const response = await fetch(`/api/orders?${params}`); // properly encoded
new URL("/api/orders", location.origin) and url.searchParams.set("page", 3) also work.
Forms and files
// A form: let the browser build multipart data
const form = document.querySelector("form");
await fetch("/api/profile", { method: "POST", body: new FormData(form) }); // no Content-Type: the browser sets the boundary
// A file upload
const data = new FormData();
data.append("resume", fileInput.files[0]);
data.append("jobId", "42");
await fetch("/api/resumes", { method: "POST", body: data });
Do not set Content-Type yourself for FormData: the browser adds the correct multipart/form-data boundary. For URL-encoded forms, pass a URLSearchParams as the body.
Credentials and CORS
By default, cross-origin fetch does not send cookies, and same-origin fetch does. Control it with credentials:
fetch(url, { credentials: "include" }); // send cookies even cross-origin (server must allow it)
fetch(url, { credentials: "omit" }); // never send cookies
A request to another origin needs the server's CORS headers (the CORS lesson); the browser enforces it and reports a TypeError: Failed to fetch if blocked, which looks identical to being offline, so check the console and the Network panel to tell them apart. Do not use mode: "no-cors" to "fix" it: the response becomes unreadable.
Cancelling and timeouts
const controller = new AbortController();
const promise = fetch("/api/search?q=java", { signal: controller.signal });
controller.abort(); // cancels: the promise rejects with an AbortError
// A timeout in one line
const response = await fetch(url, { signal: AbortSignal.timeout(5000) }); // TimeoutError after 5 s
Cancellation matters in interfaces: when a user types in a search box, cancel the previous request so that a slow old response cannot overwrite a newer result (a race condition). In React, abort in the effect cleanup function. You can also combine signals with AbortSignal.any([a, b]).
let current;
async function search(text) {
current?.abort();
current = new AbortController();
try {
const results = await getJson(`/api/search?q=${encodeURIComponent(text)}`, { signal: current.signal });
render(results);
} catch (error) {
if (error.name !== "AbortError") showError(error); // ignore cancellations
}
}
A small reusable client
Wrap the repetitive parts once:
const API = "https://api.example.com";
export class ApiError extends Error {
constructor(status, body) {
super(body?.detail ?? `Request failed with ${status}`);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
export async function api(path, { method = "GET", body, signal } = {}) {
const response = await fetch(`${API}${path}`, {
method,
headers: {
Accept: "application/json",
...(body !== undefined && { "Content-Type": "application/json" }),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
credentials: "include",
signal: signal ?? AbortSignal.timeout(10_000),
});
const hasBody = response.status !== 204 && response.headers.get("Content-Type")?.includes("json");
const data = hasBody ? await response.json() : null;
if (!response.ok) throw new ApiError(response.status, data);
return data;
}
// usage
const order = await api("/orders/5");
await api("/orders", { method: "POST", body: { customerId: 3, productIds: [1, 2] } });
Showing loading and error states
Every network call has three outcomes that the interface must show: loading, success, error (and often empty):
async function showOrders() {
list.setAttribute("aria-busy", "true");
statusEl.textContent = "Loading orders...";
try {
const orders = await api("/orders");
statusEl.textContent = orders.length ? "" : "No orders yet.";
list.replaceChildren(...orders.map(renderOrder));
} catch (error) {
statusEl.textContent = "We could not load your orders. Please try again.";
} finally {
list.removeAttribute("aria-busy");
}
}
Use a live region (role="status") so screen readers hear the update (the accessibility lesson). Avoid showing raw error messages or stack traces to users.
Security notes
- Never put secrets in front-end code (API keys with private rights, passwords); anything in the browser is public.
- Use HTTPS; keep tokens out of URLs (they end up in logs and history).
- Escape output when rendering API data into HTML (
textContentinstead ofinnerHTML), to prevent XSS. - Treat API data as untrusted: validate its shape before use.
- Add
Authorizationthrough a central place, and handle401by signing the user out or refreshing the token.
Beyond fetch
XMLHttpRequestis the old API; usefetch.- Libraries:
axios(interceptors, automatic JSON and error handling on non-2xx),ky, and data-fetching libraries for React such as TanStack Query (caching, retries, deduplication, background refresh) and SWR. They solve caching and loading states so you do not hand-write them. - Streaming (
response.body.getReader()), Server-Sent Events (EventSource) and WebSockets for real-time updates. - Node.js 18 and later include
fetchglobally, so the same code runs on the server.
Common mistakes
- Not checking
response.ok. - Forgetting
JSON.stringifyand theContent-Typeheader when posting JSON. - Reading the body twice.
- Setting
Content-TypeforFormData. - No cancellation, so slow old responses overwrite new ones.
- Building URLs by string concatenation without
encodeURIComponentorURLSearchParams. - Treating "Failed to fetch" as a server error when it is a CORS or network problem.
- Putting secrets in the browser.
Try it yourself
- Fetch a public JSON API (for example a list of posts) and render titles into a list with
textContent. - Request a URL that returns 404 and show that the promise still fulfils; add the
response.okcheck. - POST a JSON object to a test API and read the status and
Locationheader. - Build the search-as-you-type example with
AbortControllerand watch cancelled requests in the Network panel. - Write the
api()helper and use it for three calls with loading and error states.
Check yourself
Does fetch reject its promise on a 404 or 500 response?
No; it rejects only on network-level failures. You must check response.ok or response.status.
Why must you call JSON.stringify when sending JSON with fetch?
The body must be a string (or FormData, Blob and similar); JSON.stringify converts your object, and you also set Content-Type: application/json.
How do you cancel an in-flight fetch?
Pass an AbortSignal from an AbortController (or AbortSignal.timeout(ms)) and call controller.abort(); the promise rejects with an AbortError.
Why not set Content-Type yourself when sending FormData?
The browser must generate the multipart boundary; setting the header manually breaks the request.
Interview questions
How do you handle errors with fetch?
Wrap the call in try/catch for network failures, check response.ok (or status) for HTTP errors and throw, parse the error body if present, and show appropriate messages and retry only safe requests.
How do you avoid race conditions in a search-as-you-type feature?
Debounce the input and abort the previous request with an AbortController (or ignore stale responses with a request counter), so that only the latest response updates the UI.
What is the difference between fetch and Axios?
fetch is built into browsers and Node.js and needs manual ok checks and JSON handling; Axios is a library with interceptors, automatic JSON and rejection on non-2xx status codes, at the cost of extra bytes.
Summary
fetchreturns a promise for aResponse; read the body withjson()ortext()once.- It rejects only on network failure: check
response.okandstatus. - Send JSON with
JSON.stringifyandContent-Type; useURLSearchParamsfor queries andFormDatafor forms and files. - Cancel with
AbortController, show loading, success and error states, and never expose secrets in the browser.
Going deeper
- MDN: Using the Fetch API: the complete guide.
- MDN: fetch(): options and return value.
- MDN: AbortController: cancelling requests.
- Fetch Standard: the specification.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.