Guide

Using fast-http-client

Everything the client does, with an example of each. Each section stands on its own.

Installation

Terminal
npm install fast-http-client

It runs in Node 22 or later and in every current browser. It's ESM only, ships its own TypeScript types, and has no runtime dependencies.

Quick start

ts
import { createHttp } from "fast-http-client";

export const api = createHttp({
  baseUrl: "https://api.example.com/v1",
  headers: { accept: "application/json" },
});

interface User {
  id: string;
  name: string;
}

const { data: user } = await api.get<User>("/users/42");
const { data: created } = await api.post<User>("/users", { name: "Ada" });

Create one client per API and share it. Retries, the circuit breaker and the cache all live on the client.

Making requests

ts
api.get<T>(url, options?)
api.head<T>(url, options?)
api.delete<T>(url, options?)
api.options<T>(url, options?)
api.post<T>(url, body?, options?)
api.put<T>(url, body?, options?)
api.patch<T>(url, body?, options?)
api.request<T>({ url, method, body, ...options }) // everything in one object

Each returns Promise<HttpResponse<T>>:

ts
interface HttpResponse<T> {
  status: number;
  statusText: string;
  headers: Headers;
  data: T;
  config: RequestConfig; // the config that was actually sent
  fromCache: boolean;
}
T isn't checked at runtime
T is a type assertion. If the data comes from outside your control, parse it, for example with valibot: v.parse(UserSchema, res.data).

Per-request options

OptionTypeWhat it does
queryRecord<string, QueryValue | QueryValue[]>Appended to the URL. Arrays repeat the key; null and undefined are skipped.
headersRecord<string, string>Merged over the client's headers. Names are case-insensitive.
baseUrlstringOverrides the client's base URL for this request.
timeoutMsnumberOverrides the client's timeout.
signalAbortSignalCancels the request, including any wait before a retry.
retryfalse | Partial<RetryOptions>Turns retries off, or changes them for this request.
circuitBreakerfalseSkips the circuit breaker.
cachebooleanfalse skips the cache, both reading and writing.
cacheTtlMsnumberHow long this response stays cached.
ts
await api.get("/search", {
  query: { q: "lamps", tag: ["new", "sale"], page: 2, draft: undefined },
  headers: { "x-request-id": crypto.randomUUID() },
});
// GET https://api.example.com/v1/search?q=lamps&tag=new&tag=sale&page=2

URLs

A relative url is resolved against baseUrl, and the base's path is kept: with baseUrl: "https://api.example.com/v1", both "/users" and "users" go to https://api.example.com/v1/users. An absolute URL ignores baseUrl. Without a baseUrl, a browser resolves relative URLs against the page; in Node the URL must be absolute.

Bodies

You passSent as
A plain object, array, number or booleanJSON, with content-type: application/json unless you set one
string, Blob, FormData, URLSearchParams, ArrayBuffer, a typed array, ReadableStreamAs is; the runtime sets the content type
undefined or nullNo body
Responsedata is
HEAD, or status 204, 205 or 304undefined
application/json or *+jsonThe parsed value (undefined if empty, the raw text if it isn't valid JSON)
text/*, */xml, *+xml, or no content typestring
Anything elseBlob

Errors

ThrownWhen
HttpErrorThe server answered with a status outside 200–299. Has status, statusText, data (the parsed body), headers and config.
CircuitOpenErrorThe circuit for that origin is open, so nothing was sent. Has circuit (the origin) and retryAt (epoch ms) when known.
DOMException named TimeoutErrorAn attempt ran past timeoutMs, and retries didn't help.
DOMException named AbortErrorYour signal was aborted.
TypeErrorA network failure: DNS, a refused connection, CORS.
ts
import { CircuitOpenError, HttpError } from "fast-http-client";

try {
  await api.get("/orders/7");
} catch (err) {
  if (err instanceof HttpError && err.status === 404) return null;
  if (err instanceof CircuitOpenError) {
    showBanner(`Service unavailable, retry after ${new Date(err.retryAt ?? Date.now())}`);
    return null;
  }
  throw err;
}

Timeouts and cancellation

Every attempt gets its own timeout, 10 seconds by default. With retries, a request can take longer than timeoutMs in total: each attempt has the full timeout, plus the wait between attempts.

ts
const api = createHttp({ baseUrl, timeoutMs: 5_000 });
await api.get("/reports/big", { timeoutMs: 60_000 });

A signal stops the attempt in flight and any wait before a retry. A cancelled request is never retried.

ts
const controller = new AbortController();
const promise = api.get("/search", { query: { q }, signal: controller.signal });
controller.abort(); // promise rejects with an AbortError

Retries

Retries are on by default:

OptionDefaultWhat it does
attempts3Total tries, including the first.
baseDelayMs200Base for the backoff.
maxDelayMs5000Cap on any single wait, including Retry-After.
methodsGET, HEAD, PUT, DELETE, OPTIONSOnly idempotent methods. POST and PATCH aren't retried.
statusCodes408, 425, 429, 500, 502, 503, 504Statuses worth another try.

A request is retried when it failed with one of those statuses, a network error or a timeout. It isn't retried after a cancel, when the circuit is open, or when the body is a ReadableStream, which can only be sent once.

If the response has a Retry-After header (seconds or an HTTP date), that's the wait, capped at maxDelayMs. Otherwise the wait before attempt n + 1 is a random time between 0 and min(maxDelayMs, baseDelayMs × 2^(n−1)). The randomness stops many clients retrying in step.

ts
// Client-wide
const api = createHttp({ baseUrl, retry: { attempts: 5, maxDelayMs: 10_000 } });
const noRetries = createHttp({ baseUrl, retry: false });

// Per request
await api.get("/health", { retry: false });

Per-request fields are merged over the client's, which are merged over DEFAULT_RETRY.

Circuit breaker

The client keeps one circuit per origin, so one slow service doesn't block calls to another.

  • Closed: requests go through. Consecutive failures are counted, and any success resets the count.
  • Open: after failureThreshold consecutive failures, requests fail at once with CircuitOpenError for resetTimeoutMs, without touching the network.
  • Half-open: then one trial request goes through. If it succeeds the circuit closes; if it fails, it opens again.
OptionDefaultWhat it does
failureThreshold5Consecutive failures before opening.
resetTimeoutMs30000How long it stays open before a trial.
isFailure5xx, network errors, timeoutsWhich errors count. A 4xx counts as success: the server is answering.
onStateChangeNone(circuit, from, to) => void, for logging and metrics.
ts
const api = createHttp({
  baseUrl,
  circuitBreaker: {
    failureThreshold: 3,
    onStateChange: (circuit, from, to) => console.warn(`circuit ${circuit}: ${from} → ${to}`),
  },
});

await api.get("/status", { circuitBreaker: false }); // bypass it for one request

Caching

Caching is off until you choose a store. The client then caches GET responses. One is stored only if its status is 200, its body is JSON or text, its Cache-Control has no no-store or no-cache (and no private without a cacheKey), and the request has no Authorization, Cookie or Proxy-Authorization header unless you set a cacheKey. A cached response skips the network, retries and the breaker, still runs your response interceptors, and comes back with fromCache: true.

Entries live for cacheTtlMs, 60 seconds by default. max-age and ETag aren't read; the TTL is the only rule.

A PUT, PATCH, POST or DELETE that succeeds removes the cached GET for the same URL before it resolves, so the next read goes to the server. Only that exact URL is removed: /users/1?fields=name keeps its entry until it expires.

Choosing a store

cacheStore
Not set, or falseOff
"memory"In-process, least recently used, 500 entries
"indexeddb"IndexedDB, kept across reloads; throws where there is none
An adapterYour own, such as memoryCache(…) or redisCache(…)
ts
import { createHttp, memoryCache, redisCache } from "fast-http-client";
import Redis from "ioredis";

// Browser: public data, kept across reloads
const browserApi = createHttp({ baseUrl, cache: "indexeddb", cacheTtlMs: 5 * 60_000 });

// Node, one process
const localApi = createHttp({ baseUrl, cache: memoryCache(1_000) });

// Node, shared between processes
const sharedApi = createHttp({ baseUrl, cache: redisCache(new Redis(process.env.REDIS_URL), "api:") });

// Per request
await localApi.get("/prices", { cache: false });
await localApi.get("/countries", { cacheTtlMs: 86_400_000 });

A cache that fails never fails the request: the client falls back to the network.

Cache keys and users

The key is the full URL by default. That's only safe when the response is the same for everyone who asks.

ts
const api = createHttp({
  baseUrl,
  cache: "indexeddb",
  // Runs after the request interceptors, so it sees the Authorization header they add.
  cacheKey: (config, url) => `${config.headers?.authorization ?? "anon"} ${url}`,
});

Clearing the cache

ts
await api.cache.clear();        // every entry; call it when the user logs out
await api.cache.delete("/me");  // one URL, keyed the way a GET to it would be

api.cache.delete runs your request interceptors first, so a cacheKey that reads a header they add finds the right entry. Both calls do nothing when caching is off.

Your own store

Implement CacheAdapter. The adapter is responsible for expiry: get must not return an entry older than its ttlMs.

ts
import type { CacheAdapter } from "fast-http-client";

const myCache: CacheAdapter = {
  async get(key) { /* a CacheEntry, or undefined if missing or expired */ },
  async set(key, entry, ttlMs) { /* store it; expire it after ttlMs */ },
  async delete(key) { /* remove it */ },
  async clear() { /* remove every entry this adapter stored */ },
};

Interceptors

Request interceptors run in the order they're added, each receiving the config the previous one returned, after the client's defaults are applied. They may be async. use returns a function that removes the interceptor.

ts
const stop = api.interceptors.request.use(async (config) => ({
  ...config,
  headers: { ...config.headers, authorization: `Bearer ${await getToken()}` },
}));

stop(); // removes it

A response interceptor has an optional onFulfilled and onRejected, run in order like a chain of .then(). onRejected can return a response to recover, or throw to pass the error on.

ts
api.interceptors.response.use({
  onRejected(error) {
    if (error instanceof HttpError) {
      console.error(`${error.config.method ?? "GET"} ${error.config.url} → ${error.status}`);
    }
    throw error;
  },
});

Refreshing an expired token

Give the client a refreshAuth function. When requests fail with 401, it's called once, however many are waiting. Then each request is sent once more, through the request interceptors again, so the new token is attached. If refreshAuth throws, the caller gets the original 401.

ts
let accessToken = "";

const api = createHttp({
  baseUrl,
  async refreshAuth() {
    // Plain fetch, not `api`: see the warning below
    const res = await fetch(`${baseUrl}/auth/refresh`, { method: "POST", credentials: "include" });
    if (!res.ok) throw new Error("session expired");
    accessToken = (await res.json()).accessToken;
  },
});

api.interceptors.request.use((config) => ({
  ...config,
  headers: { ...config.headers, authorization: `Bearer ${accessToken}` },
}));

How a request flows

  1. The client's defaults are merged in: baseUrl, headers, timeoutMs.
  2. Request interceptors run, in order.
  3. For a GET, the cache is checked. A hit goes straight to the response interceptors.
  4. The request is sent through the origin's circuit breaker, with a timeout and your signal. A failure worth retrying waits, then tries again.
  5. A 200 that can be cached is stored. A successful write removes the cached GET for its URL.
  6. Response interceptors run, in order, and can change the result or recover.
  7. On a 401 with refreshAuth set, the token is refreshed and the whole flow runs once more.

API reference

createHttp(options)

OptionTypeDefault
baseUrlstringNone
headersRecord<string, string>None
timeoutMsnumber10000, per attempt
retryfalse | Partial<RetryOptions>DEFAULT_RETRY
circuitBreakerfalse | Partial<BreakerOptions>DEFAULT_BREAKER
cachefalse | "memory" | "indexeddb" | CacheAdapterOff
cacheTtlMsnumber60000
cacheKey(config, url) => stringThe full URL. Without one, requests with credentials aren't cached
refreshAuth() => Promise<void>None: a 401 is just an error

Exports

ExportKind
createHttpFunction
memoryCache(maxEntries = 500)Cache adapter, least recently used
indexedDbCache(dbName?)Cache adapter
redisCache(client, prefix = "http:")Cache adapter
HttpError, CircuitOpenErrorError classes
DEFAULT_RETRY, DEFAULT_BREAKERDefault options, to read or spread
ClientOptions, HttpClient, RequestConfig, HttpResponse, and the restTypes

The full reference, with every type, is in the package README.