Skip to content
Async JavaScriptChapter 35 / 47Intermediate4 min read

Fetch API

Learn the JavaScript fetch API for GET and POST requests, JSON responses, checking res.ok, AbortController, and timeout handling, with examples.

On this page

1. What is the Fetch API?

Whether you want to get data from a server (GET) or send data (POST, PUT, DELETE), modern JavaScript uses fetch for the job. The old XMLHttpRequest is no longer needed.

fetch works in two steps: first the response headers arrive, then you read the body with res.json() or res.text(). Both give you a promise.

2. Why does it matter?

Every real app has to talk to a server: loading products, logging in, submitting a form. fetch does all of this with a simple promise-based API.

Old XMLHttpRequestfetch
A web of events and callbacksPromises, works with async await
Long setup codeA request in one line
Parse JSON yourselfThe res.json() method
Hard to cancelCancel with AbortController

3. Where is it used?

Use caseRequest
Loading a product listGET /api/products
Login / signup formPOST /api/login with a JSON body
Profile updatePATCH /api/users/1
Search as you typeAbort the old request, send a new one
File uploadPOST with a FormData body

4. How does it work?

fetch flow
Call fetch(url, options)
The request goes to the server
The response headers arrive, the promise resolves
Check res.ok
Read the body with await res.json()
Response propertyMeaning
res.oktrue if the status is between 200 and 299
res.statusA number, like 200, 404, 500
res.json()Parses the body as JSON (a promise)
res.headers.get(name)Reads a header

5. Code example

GET request with an error check

js
async function getPosts() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");

  if (!res.ok) {
    throw new Error(`Request failed: ${res.status}`);
  }

  return res.json();
}

const posts = await getPosts();
console.log(posts.map((p) => p.title));

POST JSON

js
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello", userId: 1 }),
});

const created = await res.json();
console.log(res.status, created.id);

Timeout and cancel

js
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);

cancelButton.addEventListener("click", () => controller.abort());

try {
  const res = await fetch("/api/search?q=js", { signal });
  console.log(await res.json());
} catch (error) {
  if (error.name === "TimeoutError") console.log("It took too long");
  else if (error.name === "AbortError") console.log("The user cancelled");
  else throw error;
}

How does the code work?

LineWhat is happening
if (!res.ok) throwTurned the HTTP error into a real error
method: "POST"The type of request
JSON.stringify(...)Turned the object into a text body
"Content-Type" headerTold the server the body is JSON
AbortSignal.timeout(5000)Aborts itself after 5 seconds, TimeoutError
controller.abort()Manual cancel, AbortError

6. Common mistakes

Mistake: Not checking res.ok

Why? fetch does not reject on 404 and 500, and the error page's HTML gets parsed as if it were JSON.

Better: Add if (!res.ok) throw new Error(...) on every response.

Mistake: Forgetting await before res.json()

Why? You get a pending Promise instead of the data.

Better: Write const data = await res.json().

Mistake: Sending an object directly as the body

Why? Writing body: user sends the server the text [object Object].

Better: Use JSON.stringify(user) and give the Content-Type application/json header.

Mistake: Putting API keys in frontend fetch

Why? Every user can see browser code, so the secret leaks.

Better: Send requests that need a secret through your own backend or a server route.

7. What to learn before and after

Suggested order
JSON
Promises
Async Await
Fetch API
Error Handling

Final quick revision

PointDetail
fetch(url, options)A promise of a Response
res.okThe HTTP success check, you must do it yourself
res.json()Parses the body, needs await
POSTmethod, headers, a JSON.stringify body
Cancel / timeoutAbortController, AbortSignal.timeout