Fetch API
The Fetch API is the modern, Promise-based way to make
HTTP requests in JavaScript. Whether you're loading data from
a REST endpoint, sending form data, or uploading files — fetch()
replaces the old XMLHttpRequest with a clean, readable interface
that works beautifully with async/await.
fetch() works and how it differs from XMLHttpRequest
GET, POST, PUT, and DELETE
requests
.json()
async/await with fetch() for clean code
AbortController
Why Fetch? XHR vs Fetch API
Before fetch(), developers used
XMLHttpRequest (XHR) — a callback-heavy, verbose API that's
hard to read and maintain. The Fetch API was introduced in ES2015 and returns
Promises, making it much cleaner — especially when combined
with async/await.
- Deeply nested callbacks — "callback hell"
- Manual JSON parsing everywhere
- No Promise support — no async/await
- Complex API —
open(),send(),onreadystatechange - Error handling is inconsistent and verbose
- Clean
.then()/.catch()orasync/await - Built-in
.json(),.text(),.blob()parsers - Fully Promise-based — easy to chain
- Simple options object for method, headers, body
- Supports
AbortControllerfor request cancellation
Basic Fetch — GET Request
The simplest use of fetch() is a GET request —
just pass the URL. It returns a Promise that resolves to a
Response object. To get the actual data,
you call .json() on the response, which
returns another Promise with the parsed JavaScript object.
true if status is 200–299. Always check this
before parsing data.200,
404, 500.
"OK",
"Not Found".
.get("Content-Type") to
read them.// ── Simplest GET request ──────────────────────────────────
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // parse JSON body
})
.then(data => {
console.log(data.title); // "sunt aut facere..."
console.log(data.body); // post body text
})
.catch(error => {
console.error("Fetch failed:", error.message);
});
// ── Same thing with async/await (preferred) ───────────────
async function getPost(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) throw new Error(`Error: ${response.status}`);
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Failed to fetch post:", err.message);
}
}
getPost(1);HTTP Methods — GET, POST, PUT, PATCH, DELETE
By default, fetch() makes a GET request.
To use other HTTP methods, pass a second argument — the options object
— with a method property. For POST, PUT, and PATCH,
you also provide headers and a
body containing the data to send.
const BASE = "https://jsonplaceholder.typicode.com";
// ── POST — create a new post ──────────────────────────────
async function createPost(postData) {
const res = await fetch(`${BASE}/posts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(postData) // JS object → JSON string
});
if (!res.ok) throw new Error(`POST failed: ${res.status}`);
return res.json();
}
createPost({ title: "My Post", body: "Hello world", userId: 1 })
.then(data => console.log("Created:", data.id));
// ── PUT — replace an existing post ────────────────────────
async function replacePost(id, postData) {
const res = await fetch(`${BASE}/posts/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(postData)
});
return res.json();
}
// ── PATCH — update specific fields ────────────────────────
async function patchPost(id, fields) {
const res = await fetch(`${BASE}/posts/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(fields)
});
return res.json();
}
// ── DELETE — remove a resource ────────────────────────────
async function deletePost(id) {
const res = await fetch(`${BASE}/posts/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error("Delete failed");
console.log(`Post ${id} deleted`);
}Error Handling — A Critical Gotcha
The Fetch API does NOT throw on HTTP error status codes (like 404 or 500).
It only rejects the Promise for network failures (no internet, DNS error).
This is the most common mistake developers make — you must
manually check response.ok or
response.status and throw yourself.
fetch(url, options).catch().response.ok manually.
response.ok — throw if falseok is true only for status
200–299. Throw an error for anything else.response.json(),
response.text(), or response.blob().
// ── ❌ Wrong — ignores HTTP errors ─────────────────────────
fetch("/api/user/999") // 404 — but still resolves!
.then(res => res.json()) // parses error HTML as broken JSON
.then(data => console.log(data)); // never safe
// ── ✅ Correct — always check response.ok ─────────────────
async function safeFetch(url, options = {}) {
const response = await fetch(url, options);
if (!response.ok) {
const msg = await response.text().catch(() => "");
throw new Error(`HTTP ${response.status}: ${msg || response.statusText}`);
}
return response.json();
}
// ── Using the safe wrapper ────────────────────────────────
async function loadUser(id) {
try {
const user = await safeFetch(`/api/users/${id}`);
renderUser(user);
} catch (err) {
if (err.message.includes("404")) {
showNotFound();
} else if (err.message.includes("401")) {
redirectToLogin();
} else {
showGenericError(err.message);
}
}
}Headers & Authentication
Use the headers option to set request headers.
This is where you attach auth tokens (Bearer, API keys),
declare Content-Type for the body format,
and set any custom headers your API requires.
const token = localStorage.getItem("auth_token");
// ── Setting headers with an object literal ────────────────
const res = await fetch("/api/profile", {
method: "GET",
headers: {
"Authorization": `Bearer ${token}`, // JWT auth
"Content-Type": "application/json", // body format
"X-Api-Version": "2", // custom header
"Accept": "application/json", // expect JSON back
}
});
// ── Using the Headers constructor (more flexible) ─────────
const headers = new Headers({
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
});
headers.append("X-Request-ID", crypto.randomUUID()); // add more later
const response = await fetch("/api/profile", { headers });
// ── Reading response headers ──────────────────────────────
console.log(response.headers.get("Content-Type")); // "application/json"
console.log(response.headers.get("X-RateLimit-Remaining")); // "99"Cancelling Requests with AbortController
Sometimes you need to cancel an in-flight request — for example, when a user
navigates away, clears a search input, or a component unmounts in a framework.
The AbortController API lets you attach a
signal to fetch() and call
.abort() to cancel it at any time.
// ── Basic cancel ──────────────────────────────────────────
const controller = new AbortController();
const { signal } = controller;
fetch("/api/large-data", { signal })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === "AbortError") {
console.log("Request was cancelled"); // not a real error
} else {
console.error("Fetch error:", err);
}
});
// Cancel after 3 seconds
setTimeout(() => controller.abort(), 3000);
// ── Reusable fetch with timeout ───────────────────────────
async function fetchWithTimeout(url, options = {}, ms = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(timer);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
} catch (err) {
clearTimeout(timer);
if (err.name === "AbortError") throw new Error(`Request timed out after ${ms}ms`);
throw err;
}
}
// ── Cancel previous request on new search (debounce pattern)
let searchController = null;
async function search(query) {
searchController?.abort(); // cancel previous
searchController = new AbortController();
try {
const results = await safeFetch(
`/api/search?q=${encodeURIComponent(query)}`,
{ signal: searchController.signal }
);
renderResults(results);
} catch (err) {
if (err.name !== "AbortError") showError(err);
}
}Parallel & Sequential Requests
When you need data from multiple endpoints, you have two strategies.
Sequential fetches one after another — easy but slow.
Parallel using Promise.all()
fires all requests at once and waits for all to finish — much faster when
requests are independent of each other.
const BASE = "https://jsonplaceholder.typicode.com";
// ── Sequential (slow — waits for each before starting next)
async function sequential() {
const user = await fetch(`${BASE}/users/1`).then(r => r.json());
const posts = await fetch(`${BASE}/posts?userId=1`).then(r => r.json());
const todos = await fetch(`${BASE}/todos?userId=1`).then(r => r.json());
return { user, posts, todos }; // ~3× slower
}
// ── Parallel (fast — all start at the same time) ──────────
async function parallel() {
const [user, posts, todos] = await Promise.all([
fetch(`${BASE}/users/1`).then(r => r.json()),
fetch(`${BASE}/posts?userId=1`).then(r => r.json()),
fetch(`${BASE}/todos?userId=1`).then(r => r.json()),
]);
return { user, posts, todos }; // ≈ fastest single request time
}
// ── Promise.allSettled — continue even if one fails ───────
async function resilient() {
const results = await Promise.allSettled([
fetch(`${BASE}/users/1`).then(r => r.json()),
fetch(`${BASE}/broken-endpoint`).then(r => r.json()), // will fail
fetch(`${BASE}/todos?userId=1`).then(r => r.json()),
]);
results.forEach((result, i) => {
if (result.status === "fulfilled") console.log(`[${i}] OK:`, result.value);
else console.warn(`[${i}] Failed:`, result.reason);
});
}Quick Reference — fetch() Options Object
| Option | Type | Default | Description |
|---|---|---|---|
| method | string | "GET" | HTTP method — "GET", "POST", "PUT", "PATCH", "DELETE" |
| headers | object | Headers | {} | Request headers — Content-Type, Authorization, etc. |
| body | string | FormData | Blob | null | Request body — use JSON.stringify() for JSON payloads |
| signal | AbortSignal | null | AbortController signal to cancel the request |
| mode | string | "cors" | CORS mode — "cors", "no-cors", "same-origin" |
| credentials | string | "same-origin" | Cookies handling — "omit", "same-origin", "include" |
| cache | string | "default" | Cache policy — "no-store", "reload", "force-cache", etc. |
| redirect | string | "follow" | How to handle redirects — "follow", "error", "manual" |
| keepalive | boolean | false | Allow request to outlive the page — useful for analytics beacons |
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.