Guide
Using fast-http-client
Everything the client does, with an example of each. Each section stands on its own.
Installation
npm install fast-http-clientIt 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
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
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 objectEach returns Promise<HttpResponse<T>>:
interface HttpResponse<T> {
status: number;
statusText: string;
headers: Headers;
data: T;
config: RequestConfig; // the config that was actually sent
fromCache: boolean;
}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
| Option | Type | What it does |
|---|---|---|
query | Record<string, QueryValue | QueryValue[]> | Appended to the URL. Arrays repeat the key; null and undefined are skipped. |
headers | Record<string, string> | Merged over the client's headers. Names are case-insensitive. |
baseUrl | string | Overrides the client's base URL for this request. |
timeoutMs | number | Overrides the client's timeout. |
signal | AbortSignal | Cancels the request, including any wait before a retry. |
retry | false | Partial<RetryOptions> | Turns retries off, or changes them for this request. |
circuitBreaker | false | Skips the circuit breaker. |
cache | boolean | false skips the cache, both reading and writing. |
cacheTtlMs | number | How long this response stays cached. |
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=2URLs
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 pass | Sent as |
|---|---|
| A plain object, array, number or boolean | JSON, with content-type: application/json unless you set one |
string, Blob, FormData, URLSearchParams, ArrayBuffer, a typed array, ReadableStream | As is; the runtime sets the content type |
undefined or null | No body |
| Response | data is |
|---|---|
HEAD, or status 204, 205 or 304 | undefined |
application/json or *+json | The parsed value (undefined if empty, the raw text if it isn't valid JSON) |
text/*, */xml, *+xml, or no content type | string |
| Anything else | Blob |
Errors
| Thrown | When |
|---|---|
HttpError | The server answered with a status outside 200–299. Has status, statusText, data (the parsed body), headers and config. |
CircuitOpenError | The circuit for that origin is open, so nothing was sent. Has circuit (the origin) and retryAt (epoch ms) when known. |
DOMException named TimeoutError | An attempt ran past timeoutMs, and retries didn't help. |
DOMException named AbortError | Your signal was aborted. |
TypeError | A network failure: DNS, a refused connection, CORS. |
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.
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.
const controller = new AbortController();
const promise = api.get("/search", { query: { q }, signal: controller.signal });
controller.abort(); // promise rejects with an AbortErrorRetries
Retries are on by default:
| Option | Default | What it does |
|---|---|---|
attempts | 3 | Total tries, including the first. |
baseDelayMs | 200 | Base for the backoff. |
maxDelayMs | 5000 | Cap on any single wait, including Retry-After. |
methods | GET, HEAD, PUT, DELETE, OPTIONS | Only idempotent methods. POST and PATCH aren't retried. |
statusCodes | 408, 425, 429, 500, 502, 503, 504 | Statuses 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.
// 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
failureThresholdconsecutive failures, requests fail at once withCircuitOpenErrorforresetTimeoutMs, without touching the network. - Half-open: then one trial request goes through. If it succeeds the circuit closes; if it fails, it opens again.
| Option | Default | What it does |
|---|---|---|
failureThreshold | 5 | Consecutive failures before opening. |
resetTimeoutMs | 30000 | How long it stays open before a trial. |
isFailure | 5xx, network errors, timeouts | Which errors count. A 4xx counts as success: the server is answering. |
onStateChange | None | (circuit, from, to) => void, for logging and metrics. |
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 requestCaching
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
| cache | Store |
|---|---|
Not set, or false | Off |
"memory" | In-process, least recently used, 500 entries |
"indexeddb" | IndexedDB, kept across reloads; throws where there is none |
| An adapter | Your own, such as memoryCache(…) or redisCache(…) |
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.
cacheKey is set, and a cacheKey that returns no key skips the cache rather than using the URL. Cookies the browser attaches on its own are invisible to the client, so for a cookie session, add the user's id to the key yourself or leave caching off.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
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 beapi.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.
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.
const stop = api.interceptors.request.use(async (config) => ({
...config,
headers: { ...config.headers, authorization: `Bearer ${await getToken()}` },
}));
stop(); // removes itA 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.
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.
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}` },
}));401, it waits for the refresh it's part of and never finishes. Use fetch or a separate client.How a request flows
- The client's defaults are merged in:
baseUrl,headers,timeoutMs. - Request interceptors run, in order.
- For a
GET, the cache is checked. A hit goes straight to the response interceptors. - The request is sent through the origin's circuit breaker, with a timeout and your signal. A failure worth retrying waits, then tries again.
- A 200 that can be cached is stored. A successful write removes the cached
GETfor its URL. - Response interceptors run, in order, and can change the result or recover.
- On a
401withrefreshAuthset, the token is refreshed and the whole flow runs once more.
API reference
createHttp(options)
| Option | Type | Default |
|---|---|---|
baseUrl | string | None |
headers | Record<string, string> | None |
timeoutMs | number | 10000, per attempt |
retry | false | Partial<RetryOptions> | DEFAULT_RETRY |
circuitBreaker | false | Partial<BreakerOptions> | DEFAULT_BREAKER |
cache | false | "memory" | "indexeddb" | CacheAdapter | Off |
cacheTtlMs | number | 60000 |
cacheKey | (config, url) => string | The full URL. Without one, requests with credentials aren't cached |
refreshAuth | () => Promise<void> | None: a 401 is just an error |
Exports
| Export | Kind |
|---|---|
createHttp | Function |
memoryCache(maxEntries = 500) | Cache adapter, least recently used |
indexedDbCache(dbName?) | Cache adapter |
redisCache(client, prefix = "http:") | Cache adapter |
HttpError, CircuitOpenError | Error classes |
DEFAULT_RETRY, DEFAULT_BREAKER | Default options, to read or spread |
ClientOptions, HttpClient, RequestConfig, HttpResponse, and the rest | Types |
The full reference, with every type, is in the package README.