What you'll learn: By the end of this lesson you will be able to build a request (method, URL, headers, body) in one place, explain why
fetch()resolves for a 404 and what actually makes it reject, name the four places a call can fail (before sending, with no answer, with an error status, with a success status and an unusable body), turn each into a failure kind the UI can act on, and run a tested API client that does it.
Posting a letter has more outcomes than "delivered". The envelope can be addressed wrongly, so the post office never takes it. The letter can be lost on the way. The reply can arrive saying "no such person here". Or a reply can arrive that looks fine and is written in a language you cannot read. A front end that calls an API has the same four outcomes. Most bugs in this area come from code that handles the first one and treats the rest as the same.
This is the base layer of the API module. The style choice is in Consuming REST, GraphQL and tRPC from a Client and the wire in The Request Lifecycle. The question here is narrower: what must the code around one fetch() do so that every outcome is visible?
The core idea
A call is a short pipeline, and each stage can fail in its own way.
- Build: method, URL, headers, body. Bad input can be caught before anything is sent.
- Send: the browser tries to reach the server; this can fail with no response at all.
- Receive: a response arrives with a status and headers. Any status counts as "arrived".
- Read: the body is parsed. It can be missing, cut off or not JSON.
- Check: the parsed value is compared with what the code expects.
The rule of this lesson: every stage's failure becomes data with a known kind, decided in one place, so that components never see a raw Response.
Figure 1. One call, and where it can go wrong
How to read this: the numbers mark the four places a call can fail. The component at the top gets one result, either a value or a failure kind, and never has to look inside HTTP.
Building the request
A request is four things: a method, a URL, headers and an optional body. Four rules keep it safe.
- Put the URL together in one place. A path parameter is data, not text to paste into a URL. The lab encodes each path parameter with
encodeURIComponent, so an id such as../admin?x=1stays one path segment (the demo below shows it as..%2Fadmin%3Fx%3D1). - Say what you accept and what you send.
Accepttells the server which media types the client wants, andContent-Typesays what the body is. RFC 9110 definesContent-Typeas indicating "the media type of the associated representation". A JSON body needsJSON.stringifyand aContent-Type: application/jsonheader, as MDN's examples show. - Add shared headers in one function.
Authorizationis the usual case; if every call site adds its own, one will forget. MDN adds that some headers are set by the browser and cannot be set by a script (forbidden request headers). - Know your credentials mode. MDN says that by default credentials are sent only on same-origin requests (
same-origin). A cross-origin call withincludealso needs the server's agreement, which is the subject of Same-Origin Policy and CORS.
Checking a body against its schema before sending saves a round trip: a bad body is a bug or a message for the user, and neither needs the network.
Illustration 1 (minimal example): the call everyone writes first
This follows the pattern on MDN's Using Fetch page. It is a pattern, not the lab's code.
const response = await fetch("/api/products/p-100", { headers: { accept: "application/json" } });
if (!response.ok) throw new Error(`Response status: ${response.status}`);
const product = await response.json();
It is correct for the happy path and for one failure. MDN says the promise from fetch() "will reject on some errors, such as a network error or a bad scheme", but "if the server responds with an error like 404, then fetch() fulfills with a Response". Response.ok is true when the status is in the range 200 to 299. It still leaves three gaps: a thrown Error has no kind, a 200 with an HTML body makes json() throw, and nothing stops a hanging call.
Status, headers and body: reading a response
A status code is a class and a meaning. RFC 9110 says the first digit defines the class, and describes 4xx as "the request contains bad syntax or cannot be fulfilled" and 5xx as "the server failed to fulfill an apparently valid request". The codes a front end meets most:
| Status | RFC 9110 meaning (short) | Usual front-end reaction |
|---|---|---|
| 204 | Fulfilled, no additional content to send | Success; do not try to parse a body |
| 401 | Authentication problem; the server must send a WWW-Authenticate header field |
Sign in again |
| 403 | Understood, but refused | Explain; retrying will not help |
| 404 | No current representation found; says nothing about temporary or permanent | "Not found" state |
| 502 / 503 / 504 | Gateway got an invalid reply / unavailable for now / upstream was too slow | "Try again" state |
Two response headers matter. Content-Type says how to read the body: MDN's pattern checks it before calling json(), because a sign-in page or proxy error page can arrive with a 200 and text/html. For error bodies, RFC 9457 defines problem details: JSON with media type application/problem+json and members type, title, status, detail and instance. The status member is advisory, the HTTP status decides, detail is for people and consumers should not parse it, and unknown extension members must be ignored. An error response may be plain HTML from a proxy, so a problem is read only when the content type says it is one.
Then the body is read. MDN says Response.json() rejects with a SyntaxError when the body cannot be parsed, and a body can be read only once, so reading it twice needs clone() first.
Four places to fail, as one type
The lab models every failure as data: a union type called ApiError with eight kinds, each carrying only the facts that kind has (an http error has a status and optional problem details; a timeout has the milliseconds waited).
Figure 2. Which kind a result belongs to
How to read this: follow one call from the top. The questions are asked in the order the facts become known, and every leaf except the last is a failure with its own name.
The kind decides what the person sees and whether trying again is sensible. network, timeout and 5xx are "try again" candidates; contract and not-json are bugs on someone's side and should be reported, not retried blindly; aborted should show nothing, because the user asked for it. When to retry, and how, belongs to later lessons on timeouts and retries; the client here only reports a hint.
The decision is in one function, interpret, which turns a Response and its text into a result. This excerpt is from the lab's client.ts:
function interpret<P, B, T>(endpoint: Endpoint<P, B, T>, response: Response, text: string): ApiResult<T> {
const status = response.status;
const contentType = response.headers.get("content-type");
const fail = (error: ApiError): ApiResult<T> => ({ ok: false, error });
if (!response.ok) {
// Only an explicit problem+json body is read as a problem; anything else (an HTML error page from a proxy) leaves `problem` undefined.
const problem = mediaType(contentType) === "application/problem+json" ? parseProblem(text) : undefined;
return fail({ kind: "http", status, problem, retryAfter: response.headers.get("retry-after") ?? undefined });
}
The ordering is the lesson: status first, then content type, then parse, then shape. Swapping the first two is the classic mistake (see "Break it" below).
Illustration 2 (realistic example): a product page and its API client
A shop's product page shows a product, lists reviews, and lets a signed-in user post one. Three calls, one client. Every component asks the client for an endpoint and gets back a value or a kind.
Figure 3. One client between the components and fetch
How to read this: components only talk to the client. The client alone knows headers and timeouts, and a separate function maps each failure kind to the message and the retry hint the screen uses.
Illustration 3 (failure case): the answer that was not the API
A user on a hotel network opens the product page. The network's gateway answers every request with a sign-in page and a 200. Code like Illustration 1 calls response.json() and throws a SyntaxError from inside a component: it looks like a front-end bug, while the status chart looks perfect. The client above classifies the same response as not-json, with the content type recorded. "Build it" runs this case.
Trade-offs
| Choice | Gains | Costs |
|---|---|---|
| Throw on failure | Short call sites | Failures are untyped; each caller invents its handling |
| Return a result (value or kind) | Callers must handle failure; kinds are testable | A little more code at every call site |
| One client for all calls | One place for headers, timeouts and kinds | An owner and a design to maintain |
Build it: run the failure kinds
Goal. Run the lab's client against a scripted fake fetch, and see each of the four failure places produce its own kind, together with what the screen would show.
Setup. The lab is in the course's example workspace (Node 26, pnpm). The fake fetch returns scripted replies, network errors, or calls that hang until aborted, and a manual scheduler stands in for the timer, so nothing waits.
cd examples/frontend
pnpm install
cd labs/api-client-contract
pnpm test # 60 tests in 3 files
node src/demo.ts
Steps.
- Run the tests.
contract.test.tsreplays every example response infixtures/product-api.contract.json. - Run the demo and compare with the output below. Find the 404 with problem details, the 200 that is HTML (Illustration 3), the invalid body that is never sent, and the cancel.
Expected output, captured from a real run (Node 26.12.1, 2026-11-08):
=== 200: valid product (the unknown field warehouseCode is ignored)
request: GET https://api.example.test/products/p-100
result: ok 200 {"id":"p-100","name":"Trail mug","priceCents":1250,"currency":"EUR","inStock":true}
=== 404: problem details (RFC 9457)
request: GET https://api.example.test/products/nope
result: error http 404 problem={"type":"https://example.test/problems/product-not-found","title":"Product not found","status":404,"instance":"/products/nope","extensions":{}}
shown: code=http-404 retryable=false reportAsBug=false message="We could not find that."
=== 502: an HTML page from a proxy instead of problem details
request: GET https://api.example.test/products/p-100
result: error http 502 problem=none
shown: code=http-502 retryable=true reportAsBug=true message="The server had a problem. Try again."
=== 200 with the wrong shape: price sent as a string
request: GET https://api.example.test/products/p-100
result: error contract [{"path":"$.priceCents","message":"expected integer, got string"}]
shown: code=contract retryable=false reportAsBug=true message="The server sent data this page cannot use."
=== 200 but HTML: a sign-in page answered instead of the API
request: GET https://api.example.test/products/p-100
result: error {"kind":"not-json","status":200,"contentType":"text/html"}
shown: code=not-json retryable=false reportAsBug=true message="Something between you and the server answered instead. Try again later."
=== 200 but the JSON is cut off
request: GET https://api.example.test/products/p-100
result: error {"kind":"invalid-json","status":200}
shown: code=invalid-json retryable=true reportAsBug=true message="The answer was cut off or damaged. Try again."
=== fetch itself fails (offline)
request: GET https://api.example.test/products/p-100
result: error {"kind":"network","message":"Failed to fetch"}
shown: code=network retryable=true reportAsBug=false message="Cannot reach the server. Check your connection and try again."
=== 429 with Retry-After
request: GET https://api.example.test/products/p-100
result: error http 429 problem={"type":"about:blank","title":"Too many requests","extensions":{}} retry-after=30
shown: code=http-429 retryable=true reportAsBug=false message="Too many requests. Wait a moment and try again."
=== path parameter that tries to change the URL
request: GET https://api.example.test/products/..%2Fadmin%3Fx%3D1
result: ok 200 {"id":"p-100","name":"Trail mug","priceCents":1250,"currency":"EUR","inStock":true}
=== POST with an invalid body: rejected before the network
request: (none sent)
result: error invalid-request [{"path":"$body.rating","message":"expected integer, got number"}]
shown: code=invalid-request retryable=false reportAsBug=false message="Check the highlighted fields."
=== POST with a valid body (the undeclared field isAdmin is not sent)
request: POST https://api.example.test/products/p-100/reviews body={"rating":5,"text":"Great"}
result: ok 201 {"id":"r-1","rating":5,"text":"Great"}
=== 204 with no body
request: DELETE https://api.example.test/products/p-100/reviews/r-1
result: ok 204 undefined
=== no answer within 5000 ms (virtual time)
request: GET https://api.example.test/products/p-100
result: error {"kind":"timeout","afterMs":5000}
shown: code=timeout retryable=true reportAsBug=false message="The server took too long to answer. Try again."
=== the caller cancels
request: GET https://api.example.test/products/p-100
result: error {"kind":"aborted"}
shown: code=aborted retryable=false reportAsBug=false message=""
The 502 and not-json rows show why the client keeps the status and content type with the kind. The isAdmin field is dropped from the body because the request schema does not declare it.
What the lab does not show. No browser, no real network, no React. The "offline" reply is a scripted rejection with the message Failed to fetch; real browsers word network errors differently and the lab does not claim any wording. Timeouts run on a manual scheduler, not a real clock.
Break it. In a scratch copy, change if (!response.ok) { in interpret to if (response.status >= 500) {. A 404 is now read as a success, its problem body fails the response shape, and it comes back as contract instead of http: five tests fail, including the contract replay of the 404 fixture. Restore the line and run the tests again. This is the mistake fetch invites, because it resolves for a 404 as well as for a 200.
In practice: a product page behind a flaky corporate proxy
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop's product page loads a product, its reviews and a "can I buy this" flag. Some corporate users see a blank reviews area and a console error, while the dashboards show a healthy API. The API belongs to another team.
Starting architecture
Each of six components calls fetch itself. Four check response.ok; two call json() directly, and two build URLs with template strings.
Figure 4. Six call sites, no shared rules
How to read this: each component has its own copy of the request and failure handling, so the three copies already differ.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| One shared helper that throws on failure | Status and content-type checks in one place | A day | Callers still guess what a thrown error means |
| One client returning a value or a failure kind | Every outcome is typed and testable | A few days and an owner | Needs a migration of the callers |
The decision
| Field | Decision record |
|---|---|
| Context | Six ad hoc fetch call sites; a proxy that sometimes answers with HTML; no way to tell a client bug from a server problem. |
| Decision | One API client returning a value or a failure kind, one function mapping kinds to messages and retry hints, and no fetch in components. |
| Consequences, good | One place for headers and timeouts; kinds reach the logs; tests use a fake fetch. |
| Consequences, bad | One more module to own; the first migration touches every component. |
| Revisit when | Retries or caching are needed (they belong beside this client, not in components), or when the API publishes a machine-readable contract that types can be generated from. |
Rollout and verification
- Write the failure table first: each kind, its message and its retry hint, reviewed with design.
- Migrate one screen behind a flag and compare the rate of each kind.
- Test with the fake
fetch: replay a sign-in page with200, a cut-off body, a timeout and a cancel. - Log the kind with the status, so a dashboard shows which side owns a failure.
The 2 a.m. failure
The pager fires on a spike of not-json events, while the API's own success rate is flat. The cause is a gateway change that now answers with an HTML maintenance page and status 200 for a few seconds during its deploys.
First three checks: (1) the recorded content type and first bytes of a failing body; (2) kind counts per hour against the gateway's deploy times; (3) whether the client retries these calls in a tight loop. Mitigation: show the "something between you" message and do not retry automatically. Follow-up: ask the gateway team to return a 503 for maintenance, because RFC 9110 defines 503 as "currently unable to handle the request", and alert on kind counts, not only on status.
The other side of this topic
The server's side of this conversation, how it picks status codes, shapes errors and designs endpoints so that clients can tell outcomes apart, is in the back-end lesson API Styles: REST, gRPC, GraphQL and WebSockets and in System Design: API Design. A client can only classify what the server makes distinguishable.
Architect's notes
- One client, one failure type. Its cost grows with every call site.
- Status before body, content type before parse. The order is the design.
- Keep the kind all the way to the logs. "Request failed" is not an alert you can act on.
- Treat "success with an unusable body" as a failure.
response.okcannot see it.
Common mistakes
- Assuming
fetch()rejects on 404 or 500. It resolves; only network-level failures, invalid requests (such as a bad URL) and aborts reject. - Calling
response.json()without checking the content type. An HTML page then fails as aSyntaxErrorfar from its cause. - Pasting ids into URLs. Encode each path segment.
- Adding
Authorizationat each call site. One missed call is a support ticket. - Reading a body twice. Use
clone()if you must.
Key takeaways
- A call has five stages (build, send, receive, read, check) and four places to fail.
fetch()rejects for network errors, invalid requests and aborts, not for HTTP error statuses.- Read the status first, then the content type, then parse, then check the shape.
- Model failures as data with a kind, decided in one function.
- RFC 9457 problem bodies are read only when the content type says so; the HTTP status decides, not the body's
statusmember.
Practice exercises
Exercise 1: Starter (30 min). Find every fetch call in a project. For each, write down what it does on a 404, a 502 with an HTML body, and a 200 with a body that is not JSON.
Exercise 2: Intermediate (2 hours). Write a call function that returns a value or a failure kind for those three cases plus a network failure, taking fetch as an argument. Test all four.
Exercise 3: Advanced (half day). Add a timeout and a caller cancel with one AbortController, and test that a stalled body also times out.
Related reading
In this course:
- Consuming REST, GraphQL and tRPC from a Client, the style choice and the three error models.
- The Request Lifecycle, what happens between
fetch()and the response. - Same-Origin Policy and CORS, for cross-origin calls and credentials.
- Ports and Adapters in the Front End, putting the client behind an interface the application owns.
Next in this module: API contracts and data transformation, then request cancellation, retries and timeouts (planned lessons).
Official documentation
- MDN: Using the Fetch API, rejection rules, headers, credentials, aborting and reading bodies.
- MDN: Window.fetch(), when the promise rejects.
- MDN: Response.ok and Response.json().
- RFC 9110: HTTP Semantics, status codes,
Content-Type, methods. - RFC 9457: Problem Details for HTTP APIs.