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

@vertesia/api-fetch-client

v0.82.0

Published

HTTP client which wraps a fetch implementation and simplify the creation of REST API clients. Works both in browser and in node.

Downloads

7,489

Readme

@vertesia/api-fetch-client

A lightweight HTTP client that wraps the Fetch API and simplifies building REST API clients. Works in both browser and Node.js environments.

Features

  • Fluent API for building HTTP clients
  • Works in browser and Node.js
  • Server-Sent Events (SSE) support out of the box
  • Customizable authentication via callbacks
  • Request/response interceptors
  • Custom error handling
  • TypeScript support with full type definitions

Installation

npm install @vertesia/api-fetch-client
# or
pnpm add @vertesia/api-fetch-client

Basic Usage

import { FetchClient } from '@vertesia/api-fetch-client';

const client = new FetchClient('https://api.example.com/v1');

// GET request
const data = await client.get('/users');

// POST request with payload
const newUser = await client.post('/users', {
  payload: { name: 'John', email: '[email protected]' }
});

// PUT request
await client.put('/users/123', {
  payload: { name: 'John Updated' }
});

// DELETE request
await client.delete('/users/123');

Authentication

Use the withAuthCallback method to set up dynamic authentication:

const client = new FetchClient('https://api.example.com')
  .withAuthCallback(async () => {
    const token = await getAccessToken();
    return `Bearer ${token}`;
  });

Or set headers directly:

const client = new FetchClient('https://api.example.com')
  .withHeaders({
    'Authorization': 'Bearer my-token'
  });

Query Parameters

Pass query parameters using the query option:

const results = await client.get('/search', {
  query: { q: 'search term', page: 1, limit: 10 }
});
// Request: GET /search?q=search%20term&page=1&limit=10

Custom Headers

Add headers per-request or globally:

// Global headers
const client = new FetchClient('https://api.example.com')
  .withHeaders({ 'X-Custom-Header': 'value' });

// Per-request headers
await client.get('/endpoint', {
  headers: { 'X-Request-Id': '12345' }
});

Server-Sent Events (SSE)

Stream server-sent events using the built-in SSE reader:

const stream = await client.get('/events', { reader: 'sse' });

for await (const event of stream) {
  if (event.type === 'event') {
    console.log('Event:', event.event, event.data);
  }
}

Custom Response Readers

Provide a custom reader function for non-JSON responses:

// Read as text
const text = await client.get('/file.txt', {
  reader: (response) => response.text()
});

// Read as blob
const blob = await client.get('/image.png', {
  reader: (response) => response.blob()
});

Error Handling

The client throws typed errors for different failure scenarios:

import { RequestError, ServerError, ConnectionError } from '@vertesia/api-fetch-client';

try {
  await client.get('/protected');
} catch (error) {
  if (error instanceof ServerError) {
    console.log('Server error:', error.status, error.message);
    console.log('Response payload:', error.payload);
  } else if (error instanceof ConnectionError) {
    console.log('Connection failed:', error.message);
  }
}

Custom Error Factory

Transform errors before they're thrown:

const client = new FetchClient('https://api.example.com')
  .withErrorFactory((err) => {
    if (err.status === 401) {
      return new UnauthorizedError('Please log in');
    }
    return err;
  });

Request/Response Interceptors

Hook into requests and responses for logging or modification:

const client = new FetchClient('https://api.example.com');

client.onRequest = (request) => {
  console.log('Sending:', request.method, request.url);
};

client.onResponse = (response, request) => {
  console.log('Received:', response.status, 'for', request.url);
};

Building API Clients with ApiTopic

Create organized API clients by extending ApiTopic:

import { AbstractFetchClient, ApiTopic } from '@vertesia/api-fetch-client';

class UsersApi extends ApiTopic {
  list() {
    return this.get('/');
  }

  getById(id: string) {
    return this.get(`/${id}`);
  }

  create(data: CreateUserInput) {
    return this.post('/', { payload: data });
  }
}

class MyApiClient extends AbstractFetchClient<MyApiClient> {
  readonly users: UsersApi;

  constructor(baseUrl: string) {
    super(baseUrl);
    this.users = new UsersApi(this, '/users');
  }
}

// Usage
const api = new MyApiClient('https://api.example.com');
const users = await api.users.list();
const user = await api.users.getById('123');

Non-JSON Payloads

Disable automatic JSON serialization for form data or other formats:

const formData = new FormData();
formData.append('file', fileBlob);

await client.post('/upload', {
  payload: formData,
  jsonPayload: false
});

Access Last Response

Inspect the last response for headers or status:

await client.get('/endpoint');
console.log('Status:', client.response?.status);
console.log('Headers:', client.response?.headers.get('X-Custom-Header'));

API Reference

FetchClient

The main client class for making HTTP requests.

| Method | Description | |--------|-------------| | get(path, params?) | Make a GET request | | post(path, params?) | Make a POST request | | put(path, params?) | Make a PUT request | | delete(path, params?) | Make a DELETE request | | withAuthCallback(cb) | Set authentication callback | | withHeaders(headers) | Add default headers | | withLang(locale) | Set Accept-Language header | | withErrorFactory(factory) | Set custom error factory |

Request Parameters

| Option | Type | Description | |--------|------|-------------| | query | Record<string, primitive> | Query string parameters | | headers | Record<string, string> | Request headers | | payload | object \| BodyInit | Request body | | reader | 'sse' \| function | Custom response reader | | jsonPayload | boolean | Auto-serialize payload as JSON (default: true) |

Error Classes

| Class | Description | |-------|-------------| | RequestError | Base class for all request errors | | ServerError | HTTP error responses (4xx, 5xx) | | ConnectionError | Network/connection failures |

License

Apache-2.0