Fetch API
Published by Brayan K
A deep dive into making HTTP requests, API architecture, JSON handling, security, CORS, streaming, authentication, pagination, rate limits, real-world examples, and more.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Read the response, then read its body
fetch returns a promise for a Response. Reading JSON from that response is another asynchronous operation. This first example uses a data URL containing fixed JSON, so it exercises fetch without contacting a server. Later examples construct Response fixtures to test HTTP outcomes locally. They do not test a real server’s CORS or authentication configuration.
const payload = { id: "p7", title: "Notebook" };
const url = "data:application/json," + encodeURIComponent(JSON.stringify(payload));
const response = await fetch(url); // Obtain response metadata from the embedded resource.
console.log(response.status, response.ok, response.bodyUsed);
const data = await response.json(); // Consume and parse the body once.
console.log(data.id, data.title);
console.log(response.bodyUsed);
// ✅ Expected output:
// 200 true false
// p7 Notebook
// trueThe first await obtains the response metadata. The second consumes the body and parses JSON. A response being available does not prove its status is successful, its body is valid JSON or the parsed value has the shape your application requires. Async/Await owns awaiting and rejection flow.
A failed HTTP status is still a response
For an HTTP response such as 404 or 500, fetch normally fulfils with a Response; it does not reject merely because that status indicates failure. Check ok or status before treating the body as successful data. Request or transport failures, browser access restrictions and cancellation can instead reject the fetch promise.
const response = await Promise.resolve(
new Response('{"message":"not found"}', {
status: 404,
headers: { "Content-Type": "application/json" }
})
);
console.log("response received", response.status, response.ok);
if (!response.ok) throw new Error("HTTP " + response.status);
console.log(await response.json());
// ✅ Expected output:
// response received 404 false
// ✅ Expected error:
// Error: HTTP 404The fixture above supplies the response a request might return; Promise.resolve makes its successful delivery explicit. ok means a status in the 200–299 range. It does not mean “valid JSON” or “the requested product exists.”
async function unavailableTransport() {
throw new TypeError("Transport unavailable");
}
try {
const response = await unavailableTransport();
console.log(response.status);
} catch (error) {
console.log(error.name + ": " + error.message);
}
// ✅ Expected output:
// TypeError: Transport unavailableKeep these categories separate when deciding how to report or retry a failure. Retrying every failed POST can repeat a write that already reached the server. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns retry and timeout policy.
JSON syntax and application shape are two checks
json parses the body text; it does not validate your application’s fields. Valid JSON may be null, a string or an array. A Content-Type header describes the representation, but cannot make malformed text valid JSON.
const response = new Response("not-json", {
headers: { "Content-Type": "application/json" }
});
console.log(response.ok);
try {
await response.json();
} catch (error) {
console.log(error.name);
}
console.log(response.bodyUsed);
// ✅ Expected output:
// true
// SyntaxError
// trueThe parsing error’s message can differ between engines, so this diagnostic prints the error type. The field validator below supplies its own exact message at the application boundary. Validate before destructuring or calling methods on values from an external source.
function productTitle(data) {
if (data === null || typeof data !== "object" || Array.isArray(data) ||
typeof data.title !== "string") {
throw new TypeError("product must be an object with a string title");
}
return data.title;
}
const response = new Response("null", {
headers: { "Content-Type": "application/json" }
});
const data = await response.json();
console.log(data === null);
console.log(productTitle(data));
// ✅ Expected output:
// true
// ✅ Expected error:
// TypeError: product must be an object with a string titleconst response = new Response('{"title":"Notes"}', {
headers: { "Content-Type": "text/plain" }
});
console.log(response.headers.get("content-type"));
console.log((await response.json()).title);
// ✅ Expected output:
// text/plain
// NotesA client may require the API’s promised media type before parsing; that is a contract check, not how json decides whether the text is syntactically valid. Full JSON representation and schema decisions belong to Deep Dive into JSON, Parsing & Serialization.
Consume a response body once, or clone before reading
A body is a stream. Reading it with json consumes it; reading the same body again with text does not fetch a fresh copy. bodyUsed helps show that state. A body can also be locked by a reader, so bodyUsed alone is not a universal readiness test.
const response = new Response('{"title":"Notes"}');
console.log(response.bodyUsed);
console.log((await response.json()).title);
console.log(response.bodyUsed);
try {
await response.text();
} catch (error) {
console.log(error.name);
}
// ✅ Expected output:
// false
// Notes
// true
// TypeErrorIf two consumers genuinely need the same small response, clone it before either read. Cloning tees the stream; it is not a free duplicate of arbitrarily large data, and a slow or unused branch can cause buffering. Often the simpler design is to parse once and share the parsed result.
const response = new Response('{"title":"Notes"}');
const copy = response.clone();
console.log((await response.json()).title);
console.log(await copy.text());
console.log(response.bodyUsed, copy.bodyUsed);
// ✅ Expected output:
// Notes
// {"title":"Notes"}
// true trueA 204 response has no body. Decide what that means for the endpoint before calling json. The following helper’s explicit contract treats 204 as a null result; an endpoint that promises a product on every success could instead treat it as a contract failure.
async function readOptionalJson(response) {
if (!response.ok) throw new Error("HTTP " + response.status);
if (response.status === 204) return null;
return await response.json();
}
const empty = new Response(null, { status: 204 });
console.log(empty.status, empty.ok);
console.log(await readOptionalJson(empty));
try {
await new Response(null, { status: 204 }).json();
} catch (error) {
console.log(error.name);
}
// ✅ Expected output:
// 204 true
// null
// SyntaxErrorConstruct the intended request before sending it
A Request records the URL, method, headers and body you intend to send. Constructing one does not contact the server. When an API expects JSON, stringify the data and declare that representation. The endpoint’s contract determines which method is appropriate; choosing POST alone does not make a request correct or safe to retry.
const request = new Request("https://example.invalid/products", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({ title: "Notebook", quantity: 0 })
});
console.log(request.method);
console.log(request.headers.get("content-type"));
console.log(await request.text());
// ✅ Expected output:
// POST
// application/json
// {"title":"Notebook","quantity":0}Use URL and URLSearchParams to encode query values. A literal ampersand in a search phrase must stay part of that value, rather than accidentally introducing another parameter. This example only constructs a URL.
const url = new URL("https://example.invalid/products");
url.searchParams.set("q", "red & blue");
url.searchParams.set("page", "1");
console.log(url.search);
console.log(url.searchParams.get("q"));
console.log(url.searchParams.get("page"));
// ✅ Expected output:
// ?q=red+%26+blue&page=1
// red & blue
// 1Cancellation, browser permissions and credentials have boundaries
Pass an AbortSignal to fetch when the caller needs to cancel waiting. Aborting an already-aborted signal rejects the embedded-resource request below. This demonstrates cancellation locally; aborting a real write is not proof that the server rolled it back. AbortController & Cancelling Async Work owns signal lifetimes and cancellation patterns.
const controller = new AbortController();
controller.abort();
try {
await fetch("data:text/plain,ready", { signal: controller.signal });
} catch (error) {
console.log(error.name);
}
console.log(controller.signal.aborted);
// ✅ Expected output:
// AbortError
// trueCORS is a browser-enforced sharing mechanism. The server must permit the relevant origin and request; adding mode="no-cors" is not a way to obtain readable cross-origin JSON, because an opaque response hides its body and status from JavaScript. A successful Node request does not establish that the same request will pass browser CORS checks.
Credentials and authorization need an explicit application design. Cross-origin credentials require the server’s cooperation, and secrets embedded in frontend JavaScript are visible to its users. Building Custom APIs with Fetch & Async Logic owns authenticated client boundaries; Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns broader web-security controls.
Pagination and streaming introduce their own stopping and consumption rules. Async Iterators & for-await-of owns asynchronous iteration; keep retry, pagination and caching policies out of a basic reader until their contracts are defined.
Guided exercise: read only a successful response
Complete the three blanks. Reject unsuccessful status before parsing; then await the body and return its title. The fixture is constructed locally.
async function readTitle(response) {
if (!response.___) throw new Error("HTTP " + response.status); // 👉 replace ___ with ok
const data = ___ response.json(); // 👉 replace ___ with await
return data.___; // 👉 replace ___ with title
}
console.log(await readTitle(new Response('{"title":"Notebook"}')));
try {
await readTitle(new Response("missing", { status: 404 }));
} catch (error) {
console.log(error.message);
}
// ✅ Expected output:
// Notebook
// HTTP 404Independent brief: a product reader with an explicit contract
Write readProduct(request, url). The injected request function returns a Response or rejects. Reject any non-success status with Error("HTTP " + status). A 204 success means no product and returns null. Other successes must declare application/json, allowing a semicolon parameter such as charset; reject other or missing media types with TypeError("Expected application/json"). Parse once. Require a non-null, non-array object whose id and title are strings, otherwise throw TypeError("Expected product id and title strings"). Return a new object with only id and title. Let transport and parsing errors reach the caller.
Test a valid response, 204, 404 with a non-JSON body, wrong media type, invalid JSON, valid JSON with the wrong shape and a rejecting transport. The example’s label function prints only a parsing error’s name because engine wording differs. Everything uses in-memory fixtures; it does not test a live server, CORS or authentication.
async function readProduct(request, url) {
const response = await request(url);
if (!response.ok) throw new Error("HTTP " + response.status);
if (response.status === 204) return null;
const type = response.headers.get("content-type") ?? "";
const mediaType = type.split(";")[0].trim().toLowerCase();
if (mediaType !== "application/json") {
throw new TypeError("Expected application/json");
}
const data = await response.json();
if (data === null || Array.isArray(data) || typeof data !== "object" ||
typeof data.id !== "string" || typeof data.title !== "string") {
throw new TypeError("Expected product id and title strings");
}
return { id: data.id, title: data.title };
}
const fixtures = [
["valid", () => new Response('{"id":"p1","title":"Notebook","extra":true}',
{ headers: { "Content-Type": "application/json; charset=utf-8" } })],
["empty", () => new Response(null, { status: 204 })],
["missing", () => new Response("not JSON", { status: 404 })],
["media", () => new Response('{"id":"p1","title":"Notebook"}',
{ headers: { "Content-Type": "text/plain" } })],
["syntax", () => new Response("{",
{ headers: { "Content-Type": "application/json" } })],
["shape", () => new Response('{"id":1,"title":"Notebook"}',
{ headers: { "Content-Type": "application/json" } })],
["transport", () => { throw new TypeError("Connection unavailable"); }]
];
for (const [label, make] of fixtures) {
const request = async () => make();
try {
const product = await readProduct(request, "/products/p1");
console.log(label, JSON.stringify(product));
} catch (error) {
console.log(label, error instanceof SyntaxError ? error.name : error.message);
}
}
// ✅ Expected output:
// valid {"id":"p1","title":"Notebook"}
// empty null
// missing HTTP 404
// media Expected application/json
// syntax SyntaxError
// shape Expected product id and title strings
// transport Connection unavailableThe 404 is rejected before JSON parsing, preserving the useful HTTP failure. The 204 branch is intentional, not a guess that every empty body is valid. Media-type checking is this endpoint’s contract, not something json() does for you. Returning selected fields does not make the result trusted HTML: render the title as text, as taught in DOM Manipulation.
The response has been consumed when parsing or shape validation fails. The helper performs no retry and does not suppress the error with an empty object; callers decide whether a failure should show an error message, offer a retry or be recorded. Error Handling owns recovery and rethrow decisions.
Practice quiz
What does this complete program print? const response = await Promise.resolve(new Response("missing", { status: 404 })); console.log(response.status, response.ok);
- 404 false
- 404 true
- An automatic fetch rejection
- 200 false
Answer: 404 false. A fulfilled Response can carry an unsuccessful HTTP status; ok is false for 404.
What does this complete program print? const response = new Response('{"count":0}'); console.log((await response.json()).count); console.log(response.bodyUsed);
- 0 false
- 0 true
- undefined true
- [object Promise] false
Answer: 0 true. Awaiting json produces the parsed value and consumes this response body.
What does this complete program print? const response = new Response("null"); const data = await response.json(); console.log(data === null);
- false
- SyntaxError
- true
- undefined
Answer: true. null is valid JSON. Parsing success does not promise a product object.
What does this complete program print? const response = new Response("ready"); await response.text(); try { await response.text(); } catch (error) { console.log(error.name); }
- ready
- SyntaxError
- undefined
- TypeError
Answer: TypeError. A consumed body cannot be read again. The error name is portable across the checked engines.
What does this complete program print? const response = new Response(null, { status: 204 }); console.log(response.ok); try { await response.json(); } catch (error) { console.log(error.name); }
- true SyntaxError
- false SyntaxError
- true null
- true TypeError
Answer: true SyntaxError. 204 is a successful status, but its empty body is not a JSON document.
What does this complete program print? const request = new Request("https://example.invalid/items", { method: "POST", body: JSON.stringify({ quantity: 0 }), headers: { "Content-Type": "application/json" } }); console.log(request.method); console.log(await request.text());
- GET {"quantity":0}
- POST {"quantity":0}
- POST [object Object]
- POST {"quantity":1}
Answer: POST {"quantity":0}. Request construction describes the POST and its serialized body; this program sends nothing.
What does this complete program print? const response = new Response('{"ready":true}', { headers: { "Content-Type": "text/plain" } }); console.log((await response.json()).ready);
- false
- TypeError
- true
- undefined
Answer: true. json parses the body; it does not enforce that Content-Type was application/json.
What does this complete program print? const controller = new AbortController(); controller.abort(); try { await fetch("data:text/plain,ready", { signal: controller.signal }); } catch (error) { console.log(error.name); }
- ready
- TypeError
- false
- AbortError
Answer: AbortError. The already-aborted signal causes this local fetch to reject with AbortError.
Continue this course
- Previous: Async/Await
- Next: Error Handling — Catch and handle errors with try/catch and graceful fallbacks
- Quick reference: JavaScript cheat sheet
- From the blog: Async/Await in JavaScript Explained · How to Learn to Code Fast (Without Burning Out)