hoddy-fetch-client
v1.0.2
Published
just like axios for making api request but uses the fetch API in the background
Readme
hoddy-fetch-client
A lightweight, promise-based HTTP client that delivers an Axios-style developer experience on top of the native fetch API. It handles defaults, interceptors, request cancellation, automatic response parsing, and TypeScript-first ergonomics out of the box.
Motivation
This package was born out of building React Native apps that rely heavily on network calls. In production, I repeatedly hit a frustrating issue: whenever a request was in flight, if I backgrounded the app (for example, by switching to another app) and then returned, React Native would unpredictably surface the dreaded Network request failed error. The behavior was sporadic and there was no reliable community fix—most advice boiled down to “retry and hope.” hoddy-fetch-client is my attempt to wrap the platform fetch API with saner defaults, richer retries and cancellation primitives, and better visibility so I can mitigate those transient failures and keep my app resilient.
Features
- Familiar, Axios-inspired instance API (
fetchClient.get,fetchClient.post, …) - Global and per-request defaults with deep config merging and header normalization
- Request and response interceptors with fine-grained control (
runWhen, eject, clear) - Automatic URL building (
baseURL,params) and smart response-type detection - Built-in timeout support via
AbortControllerplus manual cancellation hooks - Pluggable request/response transformers and custom adapter hook for advanced scenarios
- First-class TypeScript definitions for configs, responses, and errors
Installation
# npm
npm install hoddy-fetch-client
# yarn
yarn add hoddy-fetch-client
# pnpm
pnpm add hoddy-fetch-clientRequires an environment with a global fetch implementation (modern browsers, Node.js ≥ 18, Bun, Deno, or a polyfill such as undici).
Quick Start
import fetchClient from "hoddy-fetch-client";
fetchClient.defaults.baseURL = "https://api.example.com";
fetchClient
.get("/users", {
params: { page: 1 },
})
.then((response) => {
console.log(response.data);
});Creating Custom Instances
import { createInstance } from "hoddy-fetch-client";
const api = createInstance({
baseURL: "https://api.internal.example",
headers: {
common: {
Authorization: "Bearer <token>",
},
},
});
api.post("/widgets", { name: "Widget" });Each instance maintains isolated defaults, interceptors, and configuration.
Request Methods
All HTTP helpers return a Promise<FetchClientResponse<T>> and accept the same config shape:
fetchClient.request(config);
fetchClient.get(url, config);
fetchClient.delete(url, config);
fetchClient.head(url, config);
fetchClient.options(url, config);
fetchClient.post(url, data?, config);
fetchClient.put(url, data?, config);
fetchClient.patch(url, data?, config);Configuration Reference
| Option | Type | Description |
| --------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| url | string | Relative or absolute request URL. |
| method | FetchClientMethod | HTTP method (default "get"). |
| baseURL | string | Prepended when url is relative. |
| params | Record<string, unknown> | Query parameters (sorted, encoded). |
| headers | FetchClientHeaders \| FetchClientHeaderConfig | Common and method-specific headers. |
| data | unknown | Payload for non-bodyless methods; JSON-stringified by default. |
| body | BodyInit | Overrides data handling completely. |
| timeout | number | Milliseconds before automatic abort (uses AbortController). |
| signal | AbortSignal | External signal to cancel the request. |
| responseType | FetchClientResponseType | Force response parsing mode; otherwise auto-detected. |
| validateStatus | (status: number) => boolean | Decide whether to resolve or reject a response. |
| transformRequest | (data, headers) => BodyInit | Mutate outbound payload and headers. |
| transformResponse | (data, response) => unknown | Post-process inbound data. |
| adapter | FetchClientAdapter | Provide a custom transport (tests, SSR, mocking). |
| withCredentials | boolean | Shortcut for credentials: "include" (or "omit"). |
| Other fetch options | RequestInit fields | cache, credentials, integrity, keepalive, mode, redirect, referrer, referrerPolicy. |
Defaults are merged deeply, so you can set fetchClient.defaults.params, fetchClient.defaults.headers, etc.
Interceptors
const authInterceptorId = fetchClient.interceptors.request.use(
(config) => {
config.headers = {
...config.headers,
Authorization: `Bearer ${sessionStorage.getItem("token")}`,
};
return config;
},
(error) => Promise.reject(error),
{ runWhen: (config) => !config.headers?.Authorization }
);
const responseInterceptorId = fetchClient.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
// refresh token, redirect, etc.
}
throw error;
}
);
// Later…
fetchClient.interceptors.request.eject(authInterceptorId);
fetchClient.interceptors.response.clear();Intercepted handlers execute in registration order (request are prepended, response appended) and can return promises.
Error Handling
Errors are normalized to the FetchClientError shape and flagged with isFetchClientError.
import fetchClient, { isFetchClientError } from "hoddy-fetch-client";
try {
await fetchClient.get("/profile");
} catch (error) {
if (isFetchClientError(error)) {
console.error("Status:", error.response?.status);
console.error("Response body:", error.response?.data);
} else {
console.error("Unknown failure", error);
}
}error.config: Final request config.error.request: The constructedRequestobject.error.response: Populated for HTTP responses that failedvalidateStatus.error.code: Optional error code (e.g.,"ECONNABORTED"on timeout/abort).
Custom Adapters
Adapters let you swap out the transport layer—for SSR, deterministic tests, or platform-specific clients.
const mock = createInstance({
adapter: async (config) => {
return {
data: { hello: "world" },
status: 200,
statusText: "OK",
headers: {},
config,
request: new Request(config.url ?? "", { method: config.method }),
raw: new Response(JSON.stringify({ hello: "world" }), { status: 200 }),
};
},
});Within adapters you can reuse dispatchRequest logic or supply custom objects, provided you fulfill the FetchClientResponse contract.
Working With Timeouts & Cancellation
const controller = new AbortController();
const promise = fetchClient.get("/stream", {
timeout: 5000,
signal: controller.signal,
});
// Manual cancellation
controller.abort("user navigated away");Internally, fetchClient wires any provided signal together with its own timeout AbortController, cleaning up listeners after the request settles.
TypeScript Support
All exports ship with rich type definitions:
FetchClientRequestConfig<TData>FetchClientResponse<TData>FetchClientError<T>FetchClientInstance/createInstance- Utility guards like
isFetchClientError
Use generics to declare response shapes:
const { data } = await fetchClient.get<User[]>("/users");Building From Source
The package is built with tsup. To produce distribution artifacts:
yarn install
yarn buildThis will emit CommonJS, ESM, and type declarations to dist/.
License
MIT © Hoddy Inc
