Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Projects

Project: A Reusable API Client

Build a small reusable API client around fetch: base URL, JSON handling, typed errors, timeouts, retries with backoff and hooks. Runs live against a scripted fake server.

After a few AJAX projects you notice that every one of them contains the same fifty lines: join a base URL to a path, set JSON headers, check response.ok, parse the body, turn failures into errors, add a timeout, maybe retry. Copying that code around means copying its bugs too. The solution is to write it once, as a small client, and let the rest of the program say only what it wants: api.get('/users/1').

In this project you build that client step by step: URL building and error types first, then the core request function with timeouts and hooks, then retries with exponential backoff. It is about 120 lines of plain JavaScript with no dependencies, and it is the same shape as popular libraries, so afterwards their documentation will feel familiar. It builds directly on error handling, cancelling requests and timeouts and retries and backoff.

Every example here runs in the console panel. They talk to a scripted fake fetch: you tell it in advance what the next responses will be ("503, then 503, then 200"), and it also records the requests it received. That makes timeouts, outages and retries easy to reproduce, which is how you would unit-test a real client too.

The design

The client is created by a factory function that captures its settings in a closure:

JavaScript
const api = createClient({ baseUrl: 'https://api.example.com/v1', timeoutMs: 5000, retries: 2 });
const user = await api.get('/users/1', { query: { expand: 'company' } });

What happens inside request():

flowchart TD
  A["request(method, path, options)"] --> B["Build URL, headers and JSON body"]
  B --> C["Run beforeRequest hooks"]
  C --> D["fetch with timeout and caller signal"]
  D --> E["Run afterResponse hooks"]
  E --> F{"response.ok?"}
  F -->|"yes"| G["Parse body, return data"]
  F -->|"no"| H["Throw HttpError"]
  D -->|"timeout or network failure"| I["Throw TimeoutError or NetworkError"]
  H --> J{"Retryable and attempts left?"}
  I --> J
  J -->|"yes"| K["onRetry hooks, wait, try again"]
  K --> D
  J -->|"no"| L["onError hooks, throw to caller"]

One request passes through hooks, a fetch attempt, error classification and an optional retry loop.

Four design rules shape the code:

  1. Errors are typed. A 404, a dead network and a timeout need different reactions, so each gets its own class and the caller can use instanceof or error.name.
  2. The caller's cancellation is never disguised. If the caller aborts, the original AbortError passes through untouched, because cancelling is not a failure to report.
  3. Everything environmental is injectable. fetchImpl, sleep and random can be replaced, which is what makes the client testable without a network or real waiting.
  4. Retries are conservative. Only safe, repeatable requests are retried, and only for errors that might go away.

Step 1: URLs and error types

The simplest part first. buildUrl joins a base URL, a path and optional query parameters. It must cope with trailing and leading slashes, and encode values safely, which URLSearchParams does for us. Arrays become repeated parameters, and undefined or null values are skipped so callers can pass optional filters without cleaning them up.

JS Step 1: buildUrl and error classes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the second buildUrl line: 'users/7' without a leading slash still works, and the third shows & encoded as %26 and the space as +. Subclassing Error and setting name gives readable stack traces and lets instanceof distinguish failure kinds. The cause option keeps the original error attached for debugging.

Step 2: the core client with timeouts and hooks

Now the heart: request(). Read it in four parts.

Building the request. Headers are layered: library defaults, then the client's headers, then the per-call headers. A body option is serialized with JSON.stringify and gets a Content-Type automatically, so callers pass plain objects.

One attempt. Each attempt creates AbortSignal.timeout(timeoutMs) and, if the caller supplied a signal, combines the two with AbortSignal.any([...]). If fetch rejects, the client decides why: the caller's signal aborted (rethrow as is), the timeout signal aborted (TimeoutError), or anything else (NetworkError).

Reading the body. A 204 has no body, a JSON content type is parsed, anything else is returned as text. Error responses are parsed leniently, so a server that sends an HTML error page still produces an HttpError instead of a confusing parse failure.

Hooks. beforeRequest hooks may change the request context (adding an Authorization header is the classic use). afterResponse hooks see every response, for logging or metrics. onError hooks see the final failure.

JS Step 2: the core client

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check each line of output against the design. The 404 carries the parsed error body, so a caller can show "No such user" without parsing anything. The hanging request becomes a TimeoutError after 50 ms, but the caller-aborted one is a plain AbortError: the client did not wrap it. The invalid JSON on a 200 response surfaces as a SyntaxError, which is deliberate: a successful status with an unreadable body is a server bug and must not be silently ignored.

AbortSignal.timeout() and AbortSignal.any() are available in all current browsers and in modern Node versions. If you must support older ones, create an AbortController yourself and call abort() from a setTimeout, clearing the timer when the request ends.

Step 3: retries with exponential backoff

Some failures are temporary: a server restarting (503), a rate limit (429), a flaky connection. Retrying often succeeds, but a careless retry can do damage, so the rules matter.

  • Retry only idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS). Repeating a POST could create two orders. A PUT or DELETE leaves the same final state however many times it runs.
  • Retry only errors that may disappear: network failures, timeouts, and the statuses 408, 429, 500, 502, 503, 504. A 404 or 422 will fail the same way again.
  • Wait longer each time (exponential backoff), with jitter, a random part of the delay that stops many clients from retrying in lockstep and hammering a recovering server.
  • Respect Retry-After. If a 429 or 503 says how long to wait, believe it.
  • Cap everything: a maximum number of attempts and a maximum delay.

The function retryDelay implements "equal jitter": half of the exponential delay is fixed, the other half is random. With random injected as () => 0.5, the delays are exact and the demo is reproducible.

JS Step 3: the complete client with retries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output tells the whole story. In the first scenario three requests are sent and the waits are [75, 150]: attempt 0 has an exponential delay of 100 ms (half fixed, half random, and random is 0.5, giving 75), attempt 1 has 200 ms (giving 150). The POST and the 404 are sent exactly once. The 429 waits exactly the 2000 ms the server asked for, not our own formula. And the final line shows the cap: with retries: 3 and nothing but failures, the client makes four requests (one plus three retries) and then gives up with the last error, so the caller always learns what finally went wrong.

Using the client for real

Swap the fake for the real fetch: that is the default, so you omit fetchImpl entirely.

JavaScript
const api = createClient({
  baseUrl: 'https://api.example.com/v1',
  timeoutMs: 6000,
  retries: 2,
  hooks: {
    beforeRequest: [(ctx) => { ctx.headers.Authorization = 'Bearer ' + getAccessToken(); }],
    afterResponse: [(response) => { if (response.status === 401) signOutLocally(); }],
    onError: [(error) => reportToMonitoring(error)],
  },
});

try {
  const user = await api.get('/users/42');
  showUser(user);
} catch (error) {
  if (error instanceof HttpError && error.status === 404) showNotFound();
  else if (error instanceof TimeoutError || error instanceof NetworkError) showOffline();
  else throw error;
}

Notice how little the calling code knows about HTTP: no headers, no response.ok, no JSON.parse. That is the point of the abstraction. Two cautions. First, a token read from getAccessToken() belongs in memory or a secure cookie, not in code (AJAX security). Second, a client in a page on another origin still depends on the server's CORS rules (headers, auth and CORS).

Ideas to extend it

  1. Request cancellation by key: keep a map of in-flight controllers so a new search cancels the previous one.
  2. Response caching for GET requests, keyed by URL (caching and polling).
  3. Validation: pass an optional parse(data) function per call that checks the shape before returning (validating JSON data).
  4. Token refresh: on a 401, an afterResponse hook could refresh the token once and replay the request.
  5. Use it in an earlier project, such as the to-do app: replace its small api() function with this client.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the client rethrow the original AbortError when the caller's signal was aborted, instead of wrapping it?

    If the caller cancels, they already know why the request ended. Disguising it as a NetworkError would trigger error handling and retries for something that was intentional.
  2. 2. Which request should NOT be retried automatically after a 503?

    POST is not idempotent: repeating it can create a second order. GET, PUT and DELETE leave the same final state however often they run.
  3. 3. What is the purpose of jitter in exponential backoff?

    Without randomness, every client that failed together would retry together, repeating the overload. A random component spreads them out.
  4. 4. A server answers 429 with a Retry-After: 2 header. What does this client do?

    retryDelay returns the server's value when present, because the server knows when it will be ready. The result is still capped by maxDelayMs.
  5. 5. Why are fetchImpl, sleep and random parameters of createClient?

    Injecting these dependencies lets you script responses, skip real waiting and fix the random jitter, which makes timeouts and retries easy to test.

Summary

  • Write the fetch boilerplate once: build the URL, send JSON, parse the body, throw typed errors, and the rest of the program becomes api.get('/users/1').
  • Use URLSearchParams for query strings, and skip undefined values so optional filters are easy to pass.
  • Give each failure kind its own error class: HttpError (with status and parsed body), NetworkError, TimeoutError. Pass the caller's own AbortError through unchanged.
  • Combine a per-attempt AbortSignal.timeout() with the caller's signal using AbortSignal.any().
  • Retry only idempotent methods and only errors that may go away; use exponential backoff with jitter, honor Retry-After, and cap attempts and delay.
  • Hooks (beforeRequest, afterResponse, onRetry, onError) add authentication, logging and monitoring without touching the core.
  • Inject fetch, sleep and random so the client can be tested without a network or real waiting.

Next: Practice Exercises with Solutions