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

@alisdev/axios-kit

v1.0.3

Published

Fully-featured Axios wrapper for React + TypeScript projects with token refresh, progress tracking, and React hooks

Readme

@alisdev/axios-kit

Fully-featured Axios wrapper for React + TypeScript projects — with automatic token refresh, progress tracking, and a powerful React hook.

npm version TypeScript

Features

  • 🏗️ Registry Pattern — Multiple named Axios instances, fully independent
  • 🔐 Silent Token Refresh — Automatic 401 interception & token refresh with request queuing
  • 📦 Typed HTTP Methodsget, post, put, patch, delete with full generics
  • ⬇️ Download with Progress — Speed, ETA, and auto-trigger browser download
  • ⬆️ Upload with Progress — File/FormData upload with speed tracking
  • ⚛️ React Hook (useApi) — Auto-cancel on unmount, loading/error/data state management
  • 🍪 Flexible Token StoragelocalStorage, sessionStorage, or cookie
  • 🚫 Request Cancellation — Full AbortController support
  • 🛡️ Custom ApiError — Structured error class with status, code, and data

Installation

npm install @alisdev/axios-kit axios

Note: react is a peer dependency (optional — only needed if you use useApi).

Quick Start

1. Register an Instance

// main.ts or api.config.ts
import { AxiosKit } from "@alisdev/axios-kit";

AxiosKit.register("main", {
  baseURL: import.meta.env.VITE_API_URL,
  tokenStorage: {
    type: "localStorage",
    accessTokenKey: "access_token",
    // refreshTokenKey: "refresh_token", // Optional if httpOnlyRefreshToken is true
    httpOnlyRefreshToken: true,
  },
  refreshTokenPath: "/auth/refresh",
  timeout: 15000,
});

2. Create a Service

// services/user.service.ts
import { AxiosKit, UploadProgress } from "@alisdev/axios-kit";

const api = AxiosKit.use("main");

interface IUser {
  _id: string;
  firstName: string;
  lastName: string;
  email: string;
}

export const UserService = {
  getProfile: () =>
    api.get<IUser>("/user/profile"),

  updateProfile: (data: Partial<IUser>) =>
    api.put<IUser>("/user/profile", data),

  uploadAvatar: (file: File, onProgress?: (p: UploadProgress) => void) =>
    api.upload<{ url: string }>("/user/avatar", file, { onProgress }),

  downloadReport: (onProgress?: (p: import("@alisdev/axios-kit").DownloadProgress) => void) =>
    api.download("/reports/export", { filename: "report.pdf", onProgress }),
};

3. Use in a React Component

// components/ProfilePage.tsx
import { useApi, ApiError } from "@alisdev/axios-kit";
import { UserService } from "@/services/user.service";
import { useState } from "react";

export function ProfilePage() {
  const [form, setForm] = useState<Partial<IUser>>({});

  // Auto-fetch on mount
  const { data: profile, loading, error } = useApi(
    () => UserService.getProfile()
  );

  // Manual trigger
  const { execute: updateProfile, loading: updating } = useApi(
    () => UserService.updateProfile(form),
    { immediate: false }
  );

  const handleSubmit = async () => {
    const result = await updateProfile();
    if (result) console.log("Updated!", result);
  };

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {(error as ApiError).message}</p>;

  return (
    <div>
      <p>{profile?.firstName}</p>
      <button onClick={handleSubmit} disabled={updating}>
        Save
      </button>
    </div>
  );
}

API Reference

AxiosKit

| Method | Description | |---|---| | AxiosKit.register(name, config) | Register a new named instance | | AxiosKit.use(name) | Retrieve a registered instance | | AxiosKit.unregister(name) | Remove a registered instance | | AxiosKit.clearAll() | Remove all registered instances |

HTTP Methods

| Method | Signature | |---|---| | get<T> | (url, options?) → Promise<T> | | post<T> | (url, data?, options?) → Promise<T> | | put<T> | (url, data?, options?) → Promise<T> | | patch<T> | (url, data?, options?) → Promise<T> | | delete<T> | (url, options?) → Promise<T> |

Transfer Methods

| Method | Signature | |---|---| | download | (url, options?) → Promise<Blob> | | upload<T> | (url, data: File \| FormData, options?) → Promise<T> |

useApi<T> Hook

const { data, loading, error, execute } = useApi(fn, options?);

| Option | Type | Default | Description | |---|---|---|---| | immediate | boolean | true | Auto-execute on mount |

ApiError

| Property | Type | Description | |---|---|---| | status | number | HTTP status code (0 for network errors) | | code | string | Error code (e.g. "TOKEN_EXPIRED", "NETWORK_ERROR") | | data | unknown | Server response body | | originalError | unknown | Raw Axios error |

AxiosKitConfig

interface AxiosKitConfig {
  baseURL: string;
  tokenStorage?: {
    type: "localStorage" | "sessionStorage" | "cookie";
    accessTokenKey: string;
    refreshTokenKey?: string;
    httpOnlyRefreshToken?: boolean;
    cookieOptions?: {
      expires?: number;    // days
      path?: string;
      secure?: boolean;
    };
  };
  refreshTokenPath?: string;
  timeout?: number;          // default: 10000
  headers?: Record<string, string>;
}

Multiple Instances

AxiosKit.register("main", {
  baseURL: "https://api.main.com",
  tokenStorage: { type: "localStorage", accessTokenKey: "at", refreshTokenKey: "rt" },
  refreshTokenPath: "/auth/refresh",
});

AxiosKit.register("payment", {
  baseURL: "https://api.payment.com",
  tokenStorage: { type: "sessionStorage", accessTokenKey: "p_at", refreshTokenKey: "p_rt" },
  refreshTokenPath: "/auth/refresh",
});

const mainApi = AxiosKit.use("main");
const paymentApi = AxiosKit.use("payment");

Token Refresh Flow

  1. A request gets a 401 response
  2. AxiosKit pauses all in-flight requests
  3. Calls the refreshTokenPath endpoint with the refresh token
  4. Stores the new access token
  5. Retries all paused requests with the new token
  6. If refresh fails → clears tokens and throws ApiError with code: "SESSION_EXPIRED"

HTTP-Only Refresh Token

If your server uses httpOnly cookies to store the refresh token, set httpOnlyRefreshToken: true.

When this is enabled:

  1. AxiosKit will not attempt to read the refresh token using client-side JavaScript.
  2. During a 401 response, it will still trigger the refreshTokenPath endpoint (without sending a body).
  3. The request will automatically include withCredentials: true, allowing the browser to send the httpOnly cookie securely to your server.
  4. The server should respond with { accessToken: "..." }.

Error Handling

All errors are converted to ApiError:

try {
  const data = await api.get<IUser>("/user");
} catch (err) {
  const error = err as ApiError;
  
  switch (error.code) {
    case "NETWORK_ERROR":     // No internet
    case "SESSION_EXPIRED":   // Refresh token failed
    case "REQUEST_CANCELLED": // AbortController cancelled
    case "UNAUTHORIZED":      // 401 (without refresh config)
    default:
      console.log(error.status, error.message, error.data);
  }
}

License

MIT © alisdev