HTTP Client Utility Module

0.0.15 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

Initializes an AxiosClient with global configurations, sets up an error interceptor, and performs a GET request to an API endpoint.

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();

view raw JSON →