A typed fetch client
Relay’s dashboard calls Relay’s own API from a dozen places, and each call repeats the same four
mistakes. It reads the body of a 404 as if it were a Job. It has no timeout, so a stuck server
freezes a screen. It builds /jobs/${id} by hand and forgets to encode the id. And a network error
escapes as an exception that nobody catches.
This lesson builds one client that gets all four right. It uses only web-standard APIs (fetch,
Request, Response, Headers, AbortSignal), so the same code runs in Bun, Node and the browser.
The four types
Section titled “The four types”fetch(input, init?) takes a URL string or a Request, plus an optional RequestInit, and resolves
to a Response:
const headers = new Headers({ "content-type": "application/json" })const init: RequestInit = { method: "POST", headers, body: JSON.stringify({ kind: "build" }) }
const request = new Request("http://relay.test/jobs", init)const response: Response = await fetch(request)
console.log(request.method, request.url)console.log(response.status, response.headers.get("content-type"))Requestis what you send: method, URL, headers, body and an abort signal.Responseis what you get:status,ok,headersand a body you can read once.Headersis case-insensitive.headers.get("Content-Type")andget("content-type")agree, and a missing header isnull, notundefined.
fetch only rejects when there is no response
Section titled “fetch only rejects when there is no response”This is the most common fetch bug. A 404 and a 500 are successful fetches: the server answered.
The promise rejects only when no response arrived at all (DNS failure, refused connection, abort):
declare const url: string
const res = await fetch(url)if (res.ok) { // status 200-299} else if (res.status >= 400 && res.status < 500) { // the caller's fault: bad id, bad body. Retrying the same request will not help.} else { // the server's fault (5xx). Retrying later may help.}The split matters for Relay’s retry logic from M3. A 404 for a missing job should never be retried. A 503 during a deploy should. A client that treats both as “failed” cannot tell them apart.
The body is unknown
Section titled “The body is unknown”res.json() is typed Promise<any>. That any is a lie: the server can send anything. Annotate the
result as unknown so the compiler stops trusting it:
declare const res: Response
const body: unknown = await res.json()// @ts-expect-error: 'body' is of type 'unknown'body.statusres.json() can also reject, because the body may not be JSON at all (an HTML error page from a
proxy is common). Catch that case too. What to do with an unknown body is the next lesson.
Here the client only needs one rule: a parser for each endpoint turns unknown into the result type
or says no.
Typed endpoints
Section titled “Typed endpoints”Relay’s API is a closed list of routes. Describe it once as a table keyed by "METHOD /path", with
the body each route takes and the result it returns. The path params come from the key itself, with
the type from template literal types:
interface Job { readonly id: string readonly status: "queued" | "running" | "done" | "failed"}
interface Api { "GET /jobs/:id": { body: undefined; result: Job } "POST /jobs": { body: { kind: string }; result: Job }}
type Simplify<T> = { [K in keyof T]: T[K] } & {}type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : Ptype ParamName<S extends string> = S extends `:${infer Name}` ? Name : nevertype PathParams<P extends string> = Simplify<{ [K in ParamName<Segments<P>>]: string }>type PathOf<K extends string> = K extends `${string} ${infer P}` ? P : never
type Opts<K extends keyof Api> = { readonly params: PathParams<PathOf<K>> }
declare function request<K extends keyof Api>(key: K, opts: Opts<K>): Promise<Api[K]["result"]>
await request("GET /jobs/:id", { params: { id: "j1" } })// @ts-expect-error: this path has an :id param, `jobId` is not itawait request("GET /jobs/:id", { params: { jobId: "j1" } })// @ts-expect-error: no such endpointawait request("GET /job/:id", { params: { id: "j1" } })Now a typo in a path or a param name is a compile error at the call site, and the result type
follows from the key. The implementation fills each :name with encodeURIComponent(value),
because a job id with a / or a space in it would otherwise change the URL.
Timeouts
Section titled “Timeouts”fetch waits as long as the server does. AbortSignal.timeout(ms) gives a signal that aborts after
ms milliseconds, and fetch rejects when its signal aborts:
declare const url: string
const signal = AbortSignal.timeout(5000)try { await fetch(url, { signal })} catch (error) { if (signal.aborted) { // the timeout fired } else { // a network error }}To also let the caller cancel, combine signals with AbortSignal.any([caller, AbortSignal.timeout(ms)]).
M5 covers how a cancellation signal travels down a call chain.
Errors as values
Section titled “Errors as values”Every failure above is expected, so none should be an exception (M2). The client
returns a Result (M3) whose error is a union that the caller can switch on:
type ClientError = | { readonly _tag: "Network"; readonly message: string } | { readonly _tag: "Timeout"; readonly ms: number } | { readonly _tag: "Client"; readonly status: number; readonly body: unknown } | { readonly _tag: "Server"; readonly status: number } | { readonly _tag: "BadBody"; readonly status: number }
function shouldRetry(error: ClientError): boolean { switch (error._tag) { case "Network": case "Timeout": case "Server": return true case "Client": case "BadBody": return false }}Client keeps the response body, because a 400 usually explains itself ({ "error": "invalid_body" }).
BadBody means the server said 2xx but the body is not what the table promises. That is a bug in
one of the two programs, and retrying will not fix it.
A port for tests
Section titled “A port for tests”The client does not call the global fetch. It takes a function, (request: Request) => Promise<Response>,
the same idea as the ports in M5. A test passes a fake that records the request and
returns new Response(...):
type FetchFn = (request: Request) => Promise<Response>
const seen: Request[] = []const fake: FetchFn = async (request) => { seen.push(request) return new Response(JSON.stringify({ id: "j1", status: "queued" }), { status: 200 })}
await fake(new Request("http://relay.test/jobs/j1"))console.log(seen[0]?.url)Request and Response are constructors that work everywhere, so the test needs no server and no
network. Production passes fetch itself, which already has this shape.
Exercise
Section titled “Exercise”createClient(fetchFn, baseUrl) returns { request }. The starter ignores the status, the params,
the body and the timeout, and lets errors escape. Make it follow the rules in the header.
fetchrejects only when no response arrives. Checkres.okand the status yourself, and treat 4xx (do not retry) differently from 5xx (retry later).res.json()isanyin the types. Annotate itunknownand parse it.- A table of
"METHOD /path"keys types the params, the body and the result in one place. AbortSignal.timeout(ms)is the timeout. InjectfetchFnso tests usenew Response(...).- Return a
Resultwith a tagged error union, so the caller handles each failure by name.
Further reading
Section titled “Further reading”- AbortSignal.timeout() (MDN): how a timeout signal aborts a request.
- Using the Fetch API (MDN): requests, responses, bodies and errors.