HTTP Client Utility Module
util-http is a JavaScript and TypeScript utility library designed to simplify and standardize HTTP requests by providing a unified API layer over several popular underlying HTTP clients. It currently supports wrapping `Axios`, the native `Fetch API`, `Undici` for high-performance Node.js environments, and `Superagent` for isomorphic (Node.js and browser) use cases. The library is currently in an early development phase, at version 0.0.15, implying a potentially rapid release cadence with possible breaking changes between minor versions. Its primary differentiator is the ability to swap out the underlying HTTP client while maintaining a consistent `ClientConfig` for global settings and `ClientOptions` for per-request overrides, complete with robust TypeScript type definitions for enhanced developer experience. It aims to abstract away client-specific configurations and error handling into a standardized interface, allowing developers to choose their preferred backend client without changing their application's request logic.
Common errors
-
Error: Cannot find module 'axios'
cause Attempting to use `AxiosClient` without having the `axios` package installed as a dependency.fixInstall `axios`: `npm install axios` or `pnpm add axios`. -
TS2345: Argument of type '{ baseURL: string; timeout: number; ... }' is not assignable to parameter of type 'ClientConfig'.cause Incorrectly structuring the `ClientConfig` object or providing properties not defined in the interface.fixReview the `ClientConfig` interface for expected property names and types. Ensure all properties conform to the interface definition. -
TypeError: Cannot read properties of undefined (reading 'get')
cause Trying to call a request method (like `get`) on a client instance that hasn't been properly initialized or assigned.fixEnsure the client object (e.g., `new AxiosClient(...)`) is correctly instantiated and assigned to a variable before attempting to make requests.
Warnings
- breaking As of version 0.0.15, this library is in early development. Minor versions (e.g., 0.0.x to 0.0.y) may introduce breaking changes to the API surface or internal client implementations without strict adherence to SemVer principles for major versions.
- gotcha To use specific client wrappers (e.g., `AxiosClient`, `UndiciClient`, `SuperAgentClient`), you must explicitly install the corresponding underlying HTTP library as a separate dependency in your project.
- gotcha There is a distinction between `ClientConfig` (global settings passed to the constructor) and `ClientOptions` (per-request settings). `ClientOptions` will always override `ClientConfig` for any conflicting properties.
Install
-
npm install util-http -
yarn add util-http -
pnpm add util-http
Imports
- AxiosClient
const AxiosClient = require('util-http').AxiosClient;import { AxiosClient } from 'util-http'; - HttpClient
import HttpClient from 'util-http';
import { HttpClient } from 'util-http'; - ClientConfig
import type { ClientConfig } from 'util-http';
Quickstart
import { AxiosClient } from 'util-http';
interface MyApiResponse {
id: number;
name: string;
status: string;
}
const apiClient = new AxiosClient({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN ?? ''}`,
'Content-Type': 'application/json',
},
onError: (err) => {
console.error('API request failed:', err.message, err.statusCode);
// Custom error transformation or logging before re-throwing
if (err.statusCode === 401) {
console.error('Authentication error. Please re-authenticate.');
}
throw err; // Re-throw the transformed error
}
});
async function fetchData() {
try {
const response = await apiClient.get<MyApiResponse[]>('/items', {
params: { page: 1, limit: 10 },
headers: { 'X-Custom-Header': 'Hello' } // Overrides global headers
});
console.log('Fetched data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();