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 XMLHttpRequest | fetch |
|---|---|
| A web of events and callbacks | Promises, works with async await |
| Long setup code | A request in one line |
| Parse JSON yourself | The res.json() method |
| Hard to cancel | Cancel with AbortController |
3. Where is it used?
| Use case | Request |
|---|---|
| Loading a product list | GET /api/products |
| Login / signup form | POST /api/login with a JSON body |
| Profile update | PATCH /api/users/1 |
| Search as you type | Abort the old request, send a new one |
| File upload | POST with a FormData body |
4. How does it work?
| Response property | Meaning |
|---|---|
res.ok | true if the status is between 200 and 299 |
res.status | A 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
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
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
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?
| Line | What is happening |
|---|---|
if (!res.ok) throw | Turned the HTTP error into a real error |
method: "POST" | The type of request |
JSON.stringify(...) | Turned the object into a text body |
"Content-Type" header | Told 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
| Stage | Topics |
|---|---|
| Before | Promises, Async / Await, JSON |
| After | Error Handling, Forms & Validation, Debounce & Throttle |
Final quick revision
| Point | Detail |
|---|---|
fetch(url, options) | A promise of a Response |
res.ok | The HTTP success check, you must do it yourself |
res.json() | Parses the body, needs await |
| POST | method, headers, a JSON.stringify body |
| Cancel / timeout | AbortController, AbortSignal.timeout |