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

fetch-safe

v0.2.4

Published

HTTP client with explicit Result-based error handling for TypeScript

Readme

fetch-safe

npm version Publish to npm

Tiny HTTP client for TypeScript with explicit errors and no try/catch at the call site.

fetch-safe returns Result objects that still destructure like [data, err], so the simplest path stays simple while richer result helpers remain available when you need them.

import { getJson } from "fetch-safe";

const [user, err] = await getJson<User>("/api/users/1");
if (err) {
  console.error(err.message);
  return;
}
console.log(user.name);

Install

pnpm add fetch-safe

Simple HTTP

The core idea is straightforward:

  • call an HTTP helper
  • destructure [data, err]
  • return early on failure
  • keep working with typed data on success
import { getJson } from "fetch-safe";

const [user, err] = await getJson<{ id: number; name: string }>("/api/users/1");

if (err) {
  console.error(err.message);
  return;
}

console.log(user.name);

All request helpers return Promise<Result<T, FetchError>>:

| Method | Description | | --------------------------------- | ------------------------ | | getJson<T>(url, opts?) | GET → parsed JSON | | postJson<T>(url, body?, opts?) | POST JSON → parsed JSON | | putJson<T>(url, body?, opts?) | PUT JSON → parsed JSON | | patchJson<T>(url, body?, opts?) | PATCH JSON → parsed JSON | | del<T>(url, opts?) | DELETE → parsed JSON | | getText(url, opts?) | GET → raw string | | head(url, opts?) | HEAD → Headers |

You can import individual functions:

import { getJson, postJson } from "fetch-safe";

Or use the http namespace:

import { http } from "fetch-safe";

const [data, err] = await http.getJson("https://api.example.com/data");

Pass standard RequestInit options plus a timeout in milliseconds:

const [data, err] = await getJson<User>("/api/me", {
  headers: { Authorization: "Bearer token" },
  timeout: 5_000,
});

Errors

Errors are returned, not thrown.

| Error | When | | ----------------- | --------------------------------------------------------------------------- | | HttpError | Server responded with non-2xx status. Has .status, .statusText, .body | | NetworkError | DNS failure, timeout, connection refused | | ParseError | Response body is not valid JSON. Has .body with raw text | | ValidationError | Parsed JSON failed schema validation. Has .issues and .body |

import { getJson, HttpError, NetworkError, ParseError } from "fetch-safe";

const [data, err] = await getJson<User>("/api/users/1");

if (err) {
  if (err instanceof HttpError) {
    console.error(`HTTP ${err.status}: ${err.body}`);
  } else if (err instanceof NetworkError) {
    console.error("Network issue:", err.message);
  } else if (err instanceof ParseError) {
    console.error("Bad JSON:", err.body);
  }
  return;
}

console.log(data);

Schema Validation

Add a schema to validate parsed JSON at runtime. Any object with a .parse(value) method works, including Zod, Valibot, ArkType, or a hand-rolled validator.

import { z } from "zod";
import { http, ValidationError } from "fetch-safe";

const UserSchema = z.object({ id: z.number(), name: z.string() });

const [user, err] = await http.getJson("/api/users/1", { schema: UserSchema });

if (err) {
  if (err instanceof ValidationError) {
    console.error("Schema mismatch:", err.issues);
  }
  return;
}

console.log(user.name);

When validation fails, fetch-safe returns a ValidationError instead of throwing. It includes:

  • .issues — validation issues from the schema library
  • .body — the parsed value that failed validation
  • .cause — the original error thrown by .parse()

Schema validation works with all JSON methods: getJson, postJson, putJson, patchJson, and del.

Result Types

Under the hood, fetch-safe returns a Result object, not a raw tuple.

That object gives you:

  • .ok to distinguish success from failure
  • .value and .error
  • result methods like .map() and .toValueOrThrow()
  • tuple-style destructuring so the common HTTP path still looks like [data, err]

| Type | Shape | Description | | -------------- | ------------- | ----------- | | Result<T, E> | Result object | Supports .ok, .value, .error, methods, and [data, err] destructuring | | Ok<T> | Success result | ok: true, value: T, error: null | | Err<E> | Error result | ok: false, value: null, error: E |

Tuple-style destructuring still works:

const [data, error] = ok({ name: "Alice" });

if (!error) {
  console.log(data.name);
}

Object-style access is also available:

const result = ok({ name: "Alice" });

if (result.ok) {
  console.log(result.value.name);
}

If null is a meaningful success value in your app, use .ok as the authoritative discriminator.

Helpers

For simple HTTP calls, destructuring is enough. The helpers are there for transformation and composition.

Use result.map(...) when you already have a Result in hand. Use chainResult(...) when you want to start from getJson(...) directly, or when your mapper is async.

result.map(...)

Result.map(...) is synchronous. This is the right tool after you already await a request helper.

const result = await getJson<{ id: number; title: string }>("/api/todos/1");

const mapped = result.map((todo) => ({
  id: todo.id,
  title: todo.title.toUpperCase(),
}));

if (mapped.ok) {
  console.log(mapped.value.title);
}

chainResult(...)

Use chainResult when you want async-aware chaining from a Result or Promise<Result<...>>. It exists for two cases:

  • you want to start chaining from getJson(...) before await
  • your mapper returns a Promise
import { chainResult, getJson } from "fetch-safe";

const [name, err] = await chainResult(getJson<{ name: string }>("/api/users/1"))
  .map((user) => user.name)
  .toTuple();

Async mapper example:

const title = await chainResult(getJson<{ title: string }>("/api/todos/1"))
  .map(async (todo) => todo.title.toUpperCase())
  .toValueOrThrow();

Value extraction helpers

const value = await chainResult(getJson<{ name: string }>("/api/users/1")).toValue();
const valueOr = await chainResult(getJson<{ name: string }>("/api/users/1")).toValueOr("unknown");
const valueOrThrow = await chainResult(getJson<{ name: string }>("/api/users/1")).toValueOrThrow();
  • toValue() returns T | null
  • toValueOr(fallback) returns the fallback on error
  • toValueOrThrow() throws the original error on failure

If null is a meaningful success value in your app, prefer .ok, toValueOr(...), or toValueOrThrow() over toValue().

Prerequisites

Install mise for managing development tools:

brew install mise

Development

mise install          # Node 24, Bun, pnpm 10
pnpm install          # dependencies
pnpm test             # vitest
pnpm lint             # oxlint
pnpm fmt              # oxfmt
pnpm check            # tsgo type check
pnpm build            # tsdown package build
pnpm perf             # manual throughput benchmarks
pnpm perf:memory      # manual retention tests, requires --expose-gc
pnpm perf:soak        # manual mixed workload soak test

Mise Tasks

mise run typecheck    # tsgo --noEmit
mise run lint         # oxlint
mise run format-check # oxfmt --check
mise run local-ci     # all three in parallel

Manual Performance Testing

Performance and long-running reliability checks are intentionally separate from the unit suite.

  • pnpm test stays focused on correctness.
  • pnpm perf measures relative throughput for hot paths.
  • pnpm perf:memory looks for retained heap growth across batched runs.
  • pnpm perf:soak runs a mixed success and failure workload for a longer interval and shows an in-place ASCII progress bar.

The manual scripts live under perf/ as TypeScript files and execute against the built package in dist/ so they measure the published runtime shape while keeping the harness itself typed.

Each perf command has a matching pnpm pre-script, so dist/ is rebuilt from the latest source automatically before the benchmark starts.

Suggested workflow

pnpm perf
pnpm perf:memory
PERF_SOAK_MS=300000 pnpm perf:soak

pnpm perf:soak defaults to a 5 minute run when PERF_SOAK_MS is not set.

What to watch for:

  • throughput regressions compared to your last baseline
  • post-GC heap usage that keeps climbing batch after batch
  • RSS growth during the soak test that never stabilizes
  • disproportionate growth on failure-heavy runs compared to success-heavy runs

The request layer now clears its timeout timer on both success and failure paths, which matters when you stress rejected or timed out requests in long-running apps.

License

MIT