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

request-kit-client

v0.9.0

Published

Reusable authentication and API client

Readme

🚀 Request Kit Client

A flexible, TypeScript-first API client SDK that simplifies data fetching and service structure in modern frontend applications.

🌐 View Landing Page

Designed to reduce API boilerplate, improve maintainability, and support robust token, error, and file upload handling in both client and server-side apps.


✨ Features

  • Plug-and-play API client (createApiClient)
  • 🔐 Token injection with Axios interceptors or fetch
  • 🧱 Built-in modular services (Auth, User, etc.)
  • 🔧 Dynamic custom service creation with full type safety
  • 🧠 Centralized error normalization → always predictable error shape
  • 🗖 Auto Content-Type handling (JSON, FormData, text, raw)
  • 📂 Multipart form-data support (file uploads, FormData auto-detection)
  • 💪 Strong TypeScript typings with inference (req/res typing per method)
  • 🛡 401/403 Unauthorized interception with global hooks
  • 🌍 SSR & Public API compatible (token resolvers for server & client)
  • 🚀 Composable service factories with route overrides
  • 🗶 Built-in GET response caching (TTL-based)
  • ✏️ Response transformation hooks per endpoint
  • ⚙️ Global header injection + global error handler
  • Configurable service disabling (disable auth/user when not needed)
  • 🔄 Low-level HTTP fallback (api.http.get/post/...)
  • 🔗 Native query parameter support for all HTTP methods

🧱 Use Cases

  • ✅ Build modular Auth/User services with custom or default routes
  • ✅ Generate lightweight, typed API SDKs with endpoint-level control
  • ✅ Drop-in for SSR + browser apps with token handling
  • ✅ Override routes dynamically & merge with defaults
  • ✅ Inject headers globally (multi-tenant apps, API keys, etc.)
  • ✅ File upload / multipart form-data support
  • ✅ Catch and normalize errors for analytics or fallback UI
  • ✅ Query parameters for filtering, pagination, and API options

🕖 Installation

npm install request-kit-client

🚦 Getting Started

1. Create an API Client (Axios-powered)

import { createApiClient } from "request-kit-client";

const api = createApiClient({
  baseUrl: "https://api.example.com",
  getToken: () => localStorage.getItem("auth_token"),
  headers: { "x-app-id": "frontend" },
  onUnauthorized: (status) => {
    if ([401, 403].includes(status)) {
      localStorage.removeItem("auth_token");
      window.location.href = "/login";
    }
  },
  onError: (err) => {
    console.error("Global API Error:", err);
  },
  features: {
    loginVia: "both",
    enable2FA: true,
  },
});

2. Auth Service (Built-in)

const { data, error } = await api.auth?.login({ email, password });

if (data) localStorage.setItem("auth_token", data.token);

await api.auth?.logout();

3. User Service (Built-in)

// Get profile
const { data: user } = await api.user?.getProfile();

// Update profile
await api.user?.updateProfile({ name: "Jane Doe" });

4. Custom Service (Typed + Extendable)

import { createCustomService } from "request-kit-client";

const productService = createCustomService(api.http, {
  getProduct: {
    method: "get",
    endpoint: (id: string) => `/products/${id}`,
    responseType: {} as Product,
  },
  createProduct: {
    method: "post",
    endpoint: "/products",
    requestType: {} as ProductInput,
    responseType: {} as { id: string },
  },
});

const { data } = await productService.getProduct("123");

5. File Uploads (FormData / Multipart)

const fd = new FormData();
fd.append("file", fileInput.files[0]);
fd.append("meta", JSON.stringify({ uploadedBy: "admin" }));

const { data, error } = await api.http.post<{ url: string }>("/upload", fd);

if (error) console.error("Upload failed", error);
else console.log("File uploaded at", data?.url);

FormData is auto-detected — no need to manually set Content-Type.


🔁 Caching Support

// Cache GET for 5 minutes
const { data } = await api.user?.getProfile({ cacheTTL: 300000 });

🔗 Query Parameters

Native support for query parameters across all HTTP methods:

// GET with query params
const { data } = await api.http.get<User[]>("/users", {
  params: { page: 1, limit: 10, active: true },
  cacheTTL: 300000, // Cache key includes query params
});

// POST with query params
const { data } = await api.http.post<User>("/users", { name: "John" }, {
  params: { filter: "active" },
});

// PUT with query params
const { data } = await api.http.put<User>("/users/123", { name: "Jane" }, {
  params: { version: 2 },
});

// DELETE with query params
const { data } = await api.http.delete<{ deleted: boolean }>("/users/123", undefined, {
  params: { force: true },
});

Features:

  • ✅ Type-safe query parameters (string | number | boolean)
  • ✅ Automatic null/undefined filtering
  • ✅ Cache-aware (different params = different cache entries)
  • ✅ Works with both Axios and Fetch implementations
  • ✅ SSR-compatible

Note: Query parameters are automatically included in cache keys, so /users?page=1 and /users?page=2 are cached separately.


🧠 Response Transformation

const userService = createCustomService(api.http, {
  getProfile: {
    method: "get",
    endpoint: "/user/me",
    responseType: {} as UserProfile,
    transformResponse: (data) => ({
      ...data,
      fullName: data.name + " (user)",
    }),
  },
});

const { data } = await userService.getProfile();
console.log(data?.fullName); // "Jane Doe (user)"

🛡️ Error Handling

All responses have a unified shape:

{
  data: T | null,
  error: {
    message: string;
    statusCode?: number;
    isNetworkError?: boolean;
    raw?: any;
  } | null
}

Global error hook:

createApiClient({
  onError: (err) => {
    console.error("Global HTTP Error:", err);
    // Track/log/etc
  },
});

⚙️ SSR Support

getToken: (ctx) => {
  if (typeof window === "undefined") {
    return ctx?.req?.cookies?.auth_token;
  }
  return localStorage.getItem("auth_token");
},

📁 Folder Structure

src/
├── http/           # Axios + Fetch wrappers
├── services/       # Service factories (auth, user, custom)
├── utils/          # Error, cache, helpers
├── types/          # API types
└── index.ts        # SDK entrypoint

tests/
├── services/       # Service tests
├── utils/          # Utility tests
└── mocks/          # Shared mocks

🛠️ Roadmap

✅ Completed

  • Core API client (Axios + Fetch)
  • Auth and User service generators
  • FormData / multipart uploads
  • GET caching (TTL-based)
  • Route overrides
  • SSR-friendly token resolver
  • Response transformation hooks
  • Error normalization
  • Typed custom service builder
  • Disable built-in services
  • Global headers & error hooks
  • Native query parameter support

🧪 In Progress

  • Test coverage for service factories
  • Edge cases for optional request bodies

🕒 Planned

  • Retry & timeout support
  • OAuth2 support
  • Two-Factor Auth (2FA)
  • CLI for service codegen
  • React Query/Hook integration
  • Request deduplication
  • RBAC/permission integration

📜 License

MIT © Mohammed Syed Awadh


🙌 Contributing

  1. Fork the repo
  2. Run tests: npm run test
  3. Submit PRs with improvements or fixes

❤️ Why Request Kit Client?

A modern API SDK made for DX — empowering frontend developers to ship clean, reliable, and scalable apps without boilerplate.

  • Clean abstractions with full control
  • Zero-runtime custom services
  • Typed and ergonomic
  • Ideal for SaaS, admin dashboards, internal tools