The browser
fetch() and the Response
The browser's built-in function for talking to a server: it sends a request and returns a promise of the response.
Why it exists
A page almost never lives on its own: products, messages, the weather and the cart all live on a server. Requests used to be made with the clunky XMLHttpRequest, full of callbacks and events — a dozen lines of setup and easy to get wrong. fetch does the same in one function and returns a promise, so a request reads like ordinary code: const res = await fetch(url). Without server requests there would be no news feed, no search and no "Buy" button.
Where it's used
- Load data for a screen: a product catalog, a feed of posts, a user profile —
GET /api/products. - Submit a form or an order:
POST /api/orderswith a JSON body. - Update or delete a record:
PUT /api/todos/7,DELETE /api/todos/7in a to-do list. - Search suggestions while typing: a request on every change of the field (with a delay).
- Several independent requests for one screen — in parallel with Promise.all.
Syntax
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const data = await res.json();Examples
async function loadFish() {
const res = await fetch("/api/fish");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // a promise of the data
}
const order = { fishId: 1, kg: 2 };
JSON.stringify(order); // → '{"fishId":1,"kg":2}' — this is how an object goes into body// This is what the server's answer to GET /api/fish looks like:
const res = new Response('[{"name":"Salmon","price":12}]', {
status: 200,
headers: { "Content-Type": "application/json" },
});
res.ok; // → true
res.headers.get("content-type"); // → "application/json"
const fish = await res.json();
fish[0].name; // → "Salmon"Response: the status, the headers and a body you read with await res.json()// A stub server: it remembers what it was sent
const sent = [];
const fetch = async (url, options = {}) => {
sent.push({ url, method: options.method ?? "GET", body: options.body });
return new Response('{"id":101}', { status: 201 });
};
const res = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fishId: 1, kg: 2 }),
});
res.status; // → 201
sent[0].method; // → "POST"
sent[0].body; // → '{"fishId":1,"kg":2}'
(await res.json()).id; // → 101Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
fetch returns a promise right away and sends the request in the background — the page doesn't freeze. The response arrives in two stages. First come the status and headers: that's enough for the fetch promise to fulfill with a Response object (res.status, res.ok, res.headers). The body may be large and still loading, so reading it is a separate promise: res.json() reads the rest of the body and parses it as JSON, res.text() gives it as a string. The body is a stream and can be read only once (res.bodyUsed becomes true).
The fetch promise rejects (TypeError) only when there's no response at all: the network is down, the server is unreachable, or the browser blocked the request under its security rules (CORS). Any HTTP response, even 404 or 500, is a successful delivery: the promise fulfills and res.ok becomes false. What counts as an error is up to you.
The second argument holds the request options: method (GET by default), headers and body. The body is text (or a file, or FormData), so objects are turned into JSON with JSON.stringify, and the Content-Type: application/json header tells the server how to read it.
Traps
When to pick something else
Don't make a request if the data is already on the page or can be computed right there: every request means waiting. Don't send the same request dozens of times in a row (on every letter in a search box) — add a delay or a cache. And in bigger projects plain fetch is usually wrapped in a helper (getJSON) or a library (axios, ky) that checks the status, sets the headers and retries for you.
Practice
Lessons where this appears
- A call to the warehouseTale · Chapter 21 · The network: fetch and HTTP
- Why doesn't fetch fail on a 404?Why? · Chapter 21 · The network: fetch and HTTP
- The fish warehouse catalogWorkshop · Chapter 21 · The network: fetch and HTTP
- The case of the fish named undefinedInvestigation · Chapter 21 · The network: fetch and HTTP
- Building the to-do listWorkshop · Chapter 23 · Project: a to-do app
- Why split a project into layers?Why? · Chapter 29 · Final project: a weather app