npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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 AbortController plus 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-client

Requires 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 constructed Request object.
  • error.response: Populated for HTTP responses that failed validateStatus.
  • 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 build

This will emit CommonJS, ESM, and type declarations to dist/.

License

MIT © Hoddy Inc