A fetch-based HTTP client for Node.js, browsers and workers.
You stop writing base URL joins, JSON encoding, status checks and timeout plumbing around fetch,
and the typed clients for Harbor, Loki, OAuth2, Vault and VictoriaLogs run on the same core.
Documentation · Why hapic? · Packages · Installation · Quick start · Development
fetch sends a request and hands you a response. Everything around it is yours to write, in every project: joining a base URL and a query string, encoding the body as JSON, checking response.ok because a 404 resolves, choosing between .json() and .text(), wiring an AbortSignal for a timeout, retrying after a token refresh. Each service API then adds its own URLs and payload shapes on top.
hapic is that layer, written once, in a Client class that the service clients extend:
| Concern | With fetch alone |
With hapic |
|---|---|---|
| URLs | new URL(path, base) and URLSearchParams by hand at each call |
baseURL on the client, query per request; bigint values become strings |
| JSON bodies | JSON.stringify and a content-type header at each call |
plain objects are encoded and content-type / accept are set |
| Failed statuses | a 404 or 500 resolves; you check response.ok and throw yourself |
400 to 599 rejects with an HttpResponseError that carries the decoded body |
| Decoding | you pick .json() or .text(); .json() throws on an empty or HTML body |
read by responseType or Content-Type; invalid JSON falls back to text; server-sent events stay a stream |
| Auth | build Basic base64 or Bearer strings yourself |
setAuthorizationHeader({ type: 'Bearer', token }) for every request |
| Token refresh, fallbacks | wrap every call site | an error hook returns RequestOptions to retry, or a Response to resolve |
| Timeouts | combine AbortSignal.timeout() with your own signal, classify the abort |
timeout option; rejects with code ETIMEDOUT, checked by isClientErrorDueTimeout |
| Proxies | Node.js fetch does not read HTTPS_PROXY by default; you configure a dispatcher |
the proxy environment variables are read by default in Node.js |
| Tests | stub the global fetch |
MemoryTransport records requests while the real pipeline runs |
| Service APIs | hand-written URLs and payload types per endpoint | @hapic/* clients with typed domain APIs on the same Client |
The same request, two ways:
import { createClient } from 'hapic';
const token = 'my-token';
// fetch
const url = new URL('users', 'https://api.example.com/');
url.searchParams.set('notify', 'true');
const response = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
body: JSON.stringify({ name: 'Peter' }),
signal: AbortSignal.timeout(5_000),
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
const user = await response.json();
// hapic
const client = createClient({ baseURL: 'https://api.example.com/', timeout: 5_000 });
client.setAuthorizationHeader({ type: 'Bearer', token });
const { data } = await client.post('users', { name: 'Peter' }, { query: { notify: true } });Every call, from the base client or a service client, runs through one pipeline. Hooks and transformers plug into it, and an error hook can answer a failure or send the request again:
The hapic README covers each step: options, hooks, transformers, responses, timeouts, errors, transports and the instance registry.
| Package | Version | Description |
|---|---|---|
hapic |
The base client: request methods, hooks, transformers, headers and authorization, timeouts, errors, transports, proxy. | |
@hapic/harbor |
Harbor container registry: projects, repositories, artifacts, robot accounts, webhooks. | |
@hapic/loki |
Grafana Loki: push and query logs through the distributor, querier and compactor endpoints. | |
@hapic/oauth2 |
OAuth2 and OpenID Connect: authorize URLs, token requests, userinfo, provider metadata. | |
@hapic/vault |
HashiCorp Vault: key-value engines v1 and v2, mounts. | |
@hapic/victorialogs |
VictoriaLogs: ingest and query logs. |
Each service client is a <Service>Client that extends Client and groups its endpoints into domain APIs (client.project, client.robot, ...). Hooks, headers, timeouts and the is* error guards of the base client work on all of them. The Building a Service Client guide shows how to write your own.
npm install hapic --saveA service client declares hapic as a peer dependency, so install both:
npm install hapic @hapic/harbor --saveAll packages are ESM only and need Node.js >=22.0.0; the base client also runs in browsers and workers on the platform fetch.
import { createClient, isHttpResponseError } from 'hapic';
const client = createClient({
baseURL: 'https://api.example.com/',
timeout: 10_000,
});
client.setAuthorizationHeader({ type: 'Bearer', token: 'my-token' });
try {
const { data } = await client.get('users', { query: { page: 1 } });
console.log(data);
} catch (error) {
if (isHttpResponseError(error)) {
console.error(error.status, error.response?.data);
}
}A service client takes its request options under request and a credentials@host connection string:
import { HarborClient } from '@hapic/harbor';
const harbor = new HarborClient({
connectionString: 'admin:secret@https://registry.example.com/api/v2.0/',
request: { timeout: 10_000 },
});
const project = await harbor.project.getOne(1);Continue with the getting started guide or the hapic README.
npm ci # install
npm run build # build all packages (Nx, cached)
npm run test # run every package's tests (Vitest)
npm run lint # ESLint- Development needs Node.js
^24.15.0or>=26.0.0. A service client's tests import the builthapic, so runnpm run buildfirst. npm run dev --workspace=packages/docsserves the documentation site locally.
Commits follow Conventional Commits and are checked by commitlint; npm run commit opens an interactive prompt. Releases and changelogs are generated from the commit messages by release-please.
Made with 💚
Published under MIT License.