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

@kylecodes/http-client

v0.1.0

Published

A single typed fetch wrapper: structured requests in, zod-validated values out, structured errors on failure.

Downloads

98

Readme

@kylecodes/http-client

A single typed fetch wrapper: structured requests in, zod-validated values out, structured errors on failure.

  • One function. httpRequest() is the entire API. No client classes, no interceptor chains.
  • Validated by construction. Pass a zod schema and the return type is inferred from it — the network boundary is also the type boundary.
  • Structured errors. Non-2xx responses throw HttpResponseError (with status, url, and the parsed body); transport failures throw HttpNetworkError (with the original cause). Schema mismatches propagate the raw ZodError so you can inspect the issues directly.
  • Runtime-agnostic. Built on global fetch, URL, and URLSearchParams only — works on Node ≥18, Bun, Deno, and browsers. Zero dependencies besides your own zod.
  • Testable. fetch is injectable, so tests stub a Response instead of a network.

Install

npm install @kylecodes/http-client zod
# or
bun add @kylecodes/http-client zod

zod (v4) is a peer dependency — you supply the schemas, so you own the zod version.

Usage

GET with a validated response

import { httpRequest } from "@kylecodes/http-client";
import { z } from "zod";

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

// Return type is inferred from the schema: Promise<z.infer<typeof UserSchema>>
const user = await httpRequest({
  url: "https://api.example.com/users/123",
  headers: { authorization: `Bearer ${token}` },
  schema: UserSchema,
});

user.email; // string — validated at the boundary, typed everywhere after

Query params

const results = await httpRequest({
  url: "https://api.example.com/search",
  params: { q: "quarterly report", page: "2" }, // encoded for you
  schema: SearchResultsSchema,
});

POST — JSON body

await httpRequest({
  method: "POST",
  url: "https://api.example.com/notes",
  body: { title: "hello", starred: true }, // JSON-encoded, content-type set
  schema: NoteSchema,
});

POST — form-encoded body (e.g. an OAuth2 token exchange)

const TokenResponseSchema = z.object({
  access_token: z.string(),
  expires_in: z.number(),
  refresh_token: z.string().optional(),
});

const tokens = await httpRequest({
  method: "POST",
  url: "https://oauth2.example.com/token",
  encoding: "form", // urlencoded body + content-type
  body: {
    grant_type: "authorization_code",
    code,
    redirect_uri: redirectUri,
    client_id: clientId,
  },
  schema: TokenResponseSchema,
});

Error handling

import {
  httpRequest,
  HttpResponseError,
  HttpNetworkError,
} from "@kylecodes/http-client";
import { z } from "zod";

try {
  return await httpRequest({ url, schema });
} catch (err) {
  if (err instanceof HttpResponseError) {
    // A response arrived but was non-2xx.
    err.status; // 429
    err.url; // the full URL requested
    err.body; // parsed JSON body if possible, else raw text
  } else if (err instanceof HttpNetworkError) {
    // fetch itself threw — DNS failure, connection refused, …
    err.cause; // the original TypeError
  } else if (err instanceof z.ZodError) {
    // 2xx, but the body didn't match the schema. Deliberately NOT wrapped.
    err.issues;
  }
  throw err;
}

All error classes extend HttpErrorAppErrorError, so a single instanceof HttpError catches both response and network failures.

Without a schema

When you genuinely can't validate (exploratory calls, pass-through proxies), omit schema and assert the type yourself:

const raw = await httpRequest<{ items: unknown[] }>({ url });

Testing — inject fetch

The second argument carries dependencies. Tests hand in a stub and never touch the network:

import { describe, expect, test } from "bun:test"; // or vitest/jest

test("fetches the profile", async () => {
  const fetchImpl = (async () =>
    new Response(JSON.stringify({ id: "1", email: "[email protected]" }), {
      status: 200,
      headers: { "content-type": "application/json" },
    })) as unknown as typeof fetch;

  const user = await httpRequest(
    { url: "https://api/x", schema: UserSchema },
    { fetchImpl },
  );
  expect(user.email).toBe("[email protected]");
});

API

function httpRequest<S extends ZodType>(
  req: HttpRequest<S> & { schema: S },
  deps?: HttpDeps,
): Promise<z.infer<S>>;
function httpRequest<T = unknown>(
  req: HttpRequest<undefined>,
  deps?: HttpDeps,
): Promise<T>;

interface HttpRequest<S> {
  method?: "GET" | "POST";
  url: string;
  params?: Record<string, string>; // appended as a querystring
  headers?: Record<string, string>;
  body?: Record<string, unknown>;
  encoding?: "json" | "form"; // default 'json'
  schema?: S;
}

interface HttpDeps {
  fetchImpl?: typeof fetch; // default: global fetch
}

Design notes

  • BodyInit / Response are never exposed — code that decides what to request stays separate from the code that does the request.
  • Retry/backoff is intentionally not built in; httpRequest is the single choke point where a retry wrapper would attach if you need one.

Development

bun install
bun run build   # tsc → dist/ (ESM + .d.ts + source maps)
bun test

License

MIT