Tutorials JavaScript Fetch API
Ch 49 / 78
Chapter 49 Intermediate 9 min read JavaScript

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.

Advertisement
What you'll learn
How fetch() works and how it differs from XMLHttpRequest
Making GET, POST, PUT, and DELETE requests
Parsing JSON responses with .json()
Proper error handling — network errors vs HTTP error status codes
Using async/await with fetch() for clean code
Setting headers, sending JSON bodies, and using 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.

XMLHttpRequest (Old)
Verbose, callback-based, hard to chain and read.
  • 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
Fetch API (Modern)
Promise-based, concise, and pairs perfectly with async/await.
  • Clean .then()/.catch() or async/await
  • Built-in .json(), .text(), .blob() parsers
  • Fully Promise-based — easy to chain
  • Simple options object for method, headers, body
  • Supports AbortController for 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.

Response object — key properties & methods
response.ok
boolean
true if status is 200–299. Always check this before parsing data.
response.status
number
The HTTP status code — e.g. 200, 404, 500.
response.statusText
string
Human-readable status — e.g. "OK", "Not Found".
response.headers
Headers
Response headers — use .get("Content-Type") to read them.
response.json()
Promise
Parses the body as JSON. Returns a Promise with the JS object.
response.text()
Promise
Parses the body as plain text string.
response.blob()
Promise
Parses the body as a binary Blob — use for images and files.
JavaScript — Basic GET with .then()
// ── 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.

GET
Read data
Fetch a resource. No body. Idempotent — safe to repeat.
POST
Create data
Send new data to the server. Has a body. Not idempotent.
PUT
Replace data
Replace an entire resource. Body required. Idempotent.
PATCH
Update partial
Update specific fields of a resource. Partial body.
DELETE
Remove data
Delete a resource. Usually no body. Idempotent.
JavaScript — POST, PUT, DELETE Requests
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 error handling — complete flow
1
Call fetch(url, options)
Returns a Promise. The request is sent to the server.
2a
Network failure → Promise rejects
No internet, CORS blocked, DNS failure — the Promise rejects. Caught by .catch().
2b
Server responds → Promise resolves (even on 404, 500!)
Any HTTP response resolves the Promise. You must check response.ok manually.
3
Check response.ok — throw if false
ok is true only for status 200–299. Throw an error for anything else.
4
Parse response body & use data
Call response.json(), response.text(), or response.blob().
JavaScript — Proper Error Handling
// ── ❌ 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.

JavaScript — Headers & Auth Token
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"
Advertisement

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.

JavaScript — AbortController & Timeout
// ── 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.

JavaScript — Parallel Fetches with Promise.all()
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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel