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

@richardtwi-dbg/fetchly

v0.5.3

Published

A lightweight, fully typed fetch client

Readme

Fetchly

Fetchly is a lightweight, type-safe HTTP client built on top of the native Fetch API.

It removes repetitive response handling while keeping the API close to fetch.

It shares nothing but the name with the similar npm package fetchly.

const response = await fetch("/api/users");

if (!response.ok) {
  throw new Error();
}

const users = await response.json();

With Fetchly:

const users = await api.get<User[]>("/users");

Status

Fetchly is currently under active development.

Features

  • Type-safe request results
  • GET, POST, PUT, PATCH, and DELETE methods
  • Configurable base URL
  • Client-level and request-level headers
  • Query parameters
  • Automatic JSON serialization and JSON response parsing
  • Typed API errors
  • Request timeout and cancellation through AbortSignal
  • Request and response interceptors
  • Middleware and plugin API
  • Retry support for temporary server errors
  • JWT access-token refresh plugin
  • FormData plugin
  • File download helpers
  • ESM, CommonJS, and TypeScript declarations

Installation

npm install @richardtwi-dbg/fetchly

Basic usage

import { createClient } from "fetchly";

interface User {
  id: number;
  name: string;
}

const api = createClient({
  baseUrl: "/api",
});

const users = await api.get<User[]>("/users");

const user = await api.get<User>("/users/1");

Plugins

Fetchly uses middleware-based plugins for functionality that needs to control a request flow, such as retries, authentication, uploads, and caching.

Plugins can be installed after client creation:

const api = createClient();

api.use(plugin);

Or during creation:

const api = createClient({
  plugins: [pluginA, pluginB],
});

Retry

Retry temporary server failures:

const api = createClient({
  retry: {
    count: 3,
    delay: 1_000,
  },
});

By default, Fetchly retries responses with statuses 500, 502, 503, and 504.

You can customize retry statuses:

const api = createClient({
  retry: {
    count: 2,
    delay: 500,
    statuses: [429, 500, 503],
  },
});

The same option can be applied to a single request:

await api.get<User[]>("/users", {
  retry: {
    count: 2,
    delay: 250,
  },
});

JWT token refresh

Use the JWT plugin to add an access token and refresh it after a 401 response.

import { createClient, jwt } from "@richardtwi-dbg/fetchly";

let accessToken = "initial-token";

const api = createClient({
  baseUrl: "/api",
});

api.use(jwt({
  getAccessToken: () => accessToken,

  async refreshToken() {
    const response = await fetch("/api/auth/refresh", {
      method: "POST",
      credentials: "include",
    });

    if (!response.ok) {
      throw new Error("Unable to refresh access token");
    }

    const data = await response.json();
    accessToken = data.accessToken;
  },
}));

When multiple requests receive 401 simultaneously, Fetchly runs one refresh operation and waits for it before retrying the failed requests.

A request is refreshed only once. If the repeated request also returns 401, Fetchly throws ApiError.

FormData

Use the formData plugin to convert an object body into FormData.

import { createClient, formData } from "@richardtwi-dbg/fetchly";

const api = createClient();
api.use(formData());

await api.post("/users/avatar", {
  body: {
    name: "Richard",
    tags: ["typescript", "fetch"],
    profile: {
      active: true,
    },
  },
});

The example above sends these fields:

name = Richard
tags[0] = typescript
tags[1] = fetch
profile[active] = true

Fetchly does not set Content-Type manually for FormData. The browser adds the required multipart/form-data boundary automatically.

Download files

Download helpers return a Blob, response content type, and a filename when the server sends Content-Disposition.

const file = await api.download("/reports/monthly");

console.log(file.filename);
console.log(file.contentType);
console.log(file.blob);

Save a downloaded file in the browser:

const file = await api.download("/reports/monthly");

const url = URL.createObjectURL(file.blob);

const link = document.createElement("a");
link.href = url;
link.download = file.filename ?? "download";
link.click();

URL.revokeObjectURL(url);

Client configuration

const api = createClient({
  baseUrl: "/api",
  headers: {
    Authorization: "Bearer token",
  },
  timeout: 10000,
});

Configuration options:

| Option | Type | Description | |---|---|---| | baseUrl | string | Prefix added to every request path | | headers | HeadersInit | Headers sent with every request | | timeout | number | Default timeout in milliseconds |

Query parameters

const users = await api.get<User[]>("/users", {
  query: {
    page: 1,
    size: 50,
    active: true,
  },
});

The resulting request URL:

/api/users?page=1&size=50&active=true

Values equal to null or undefined are omitted.

JSON request body

const user = await api.post<User>("/users", {
  body: {
    name: "John",
  },
});

Fetchly automatically:

  • serializes the body with JSON.stringify
  • sets Content-Type: application/json
  • sets Accept: application/json

You can override default headers for an individual request:

const user = await api.post<User>("/users", {
  headers: {
    Authorization: "Bearer another-token",
  },
  body: {
    name: "John",
  },
});

Request headers take precedence over client headers.

HTTP methods

api.get<User[]>("/users");

api.post<User>("/users", {
  body: { name: "John" },
});

api.put<User>("/users/1", {
  body: { name: "John Doe" },
});

api.patch<User>("/users/1", {
  body: { name: "Jane Doe" },
});

api.delete<void>("/users/1");

Errors

Fetchly throws ApiError when the server responds with a non-success HTTP status.

import { ApiError } from "fetchly";

try {
  await api.get<User>("/users/1");
} catch (error) {
  if (error instanceof ApiError) {
    console.log(error.status);
    console.log(error.body);
    console.log(error.headers);
  }
}

ApiError contains:

| Property | Description | |---|---| | status | HTTP response status | | body | Parsed JSON body or response text | | headers | Response headers |

Timeout

Set a timeout for the whole client:

const api = createClient({
  baseUrl: "/api",
  timeout: 5000,
});

Or override it for one request:

await api.get<User[]>("/users", {
  timeout: 2000,
});

A timed-out request throws TimeoutError.

import { TimeoutError } from "fetchly";

try {
  await api.get<User[]>("/slow-endpoint");
} catch (error) {
  if (error instanceof TimeoutError) {
    console.log(error.timeout);
  }
}

Cancellation

Use a native AbortController to cancel a request.

const controller = new AbortController();

const request = api.get<User[]>("/users", {
  signal: controller.signal,
});

controller.abort();

await request;

Development

Install dependencies:

npm install

Run type checks:

npm run typecheck

Run tests:

npm test

Build the package:

npm run build

Roadmap

  • [x] Request and response interceptors.
  • [x] Retry support for temporary server errors
  • [x] JWT token refresh
  • [x] FormData upload support
  • [x] File download helpers
  • [x] Middleware API
  • [ ] Cache support and TTL
  • [ ] React hooks package
  • [ ] OpenAPI client generation
  • [ ] GitHub Actions CI
  • [x] npm publishing and release automation

License

MIT