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

use-api-kt

v1.0.0

Published

Tiny helper to manage short-lived authorization data (tokens), refresh credentials, retry failed API calls after refresh, and abort in-flight requests.

Readme

use-api-kt

A tiny, dependency-free helper for managing short-lived authorization data and safely calling APIs that require it.

This package provides a simple pattern for fetching/refreshing authorization credentials (e.g. access tokens) and using them in API calls. It handles an initial authorization fetch, optional periodic "hydration" (refresh), retrying a failed API call after refreshing credentials, and aborting in-flight requests.

Install

npm install use-api-kt
# or
yarn add use-api-kt

Quick example (TypeScript)

import { createApiManager } from "use-api-kt";

// imaginary function that fetches a fresh token
async function fetchAuth(_signal: AbortSignal) {
	const res = await fetch("https://auth.example.com/token", { signal: _signal });
	if (!res.ok) throw new Error("failed to fetch token");
	return (await res.json()).accessToken;
}

async function main() {
	const manager = await createApiManager({
		callback: fetchAuth,
		onError: (err) => {
			// called when a useApi call throws. Return true to reattempt
			// after refreshing auth data, or false to bubble the error.
			console.warn("API call failed, will reattempt after refresh", err);
			return true; // reattempt by default
		},
		// optional: refresh token every 5 minutes
		hydrationIntervalInMs: 5 * 60 * 1000,
	});

	// run an API call that needs the token
	const data = await manager.useApi(async (token, signal) => {
		const r = await fetch("https://api.example.com/me", {
			headers: { Authorization: `Bearer ${token}` },
			signal,
		});
		if (!r.ok) throw new Error("api error");
		return r.json();
	});

	console.log(data);

	// When done, which aborts any ongoing calls and closes hydrations
	manager.cleanup();
}

main().catch(console.error);

JavaScript (CommonJS) example

const { createApiManager } = require("use-api-kt");

async function fetchAuth(signal) {
	const res = await fetch("https://auth.example.com/token", { signal });
	if (!res.ok) throw new Error("failed to fetch token");
	return (await res.json()).accessToken;
}

(async () => {
	const manager = await createApiManager({ callback: fetchAuth });

	try {
		const result = await manager.useApi((token, signal) =>
			fetch("https://api.example.com/data", { headers: { Authorization: `Bearer ${token}` }, signal })
				.then(r => r.json())
		);
		console.log(result);
	} finally {
		manager.cleanup();
	}
})();

API Reference

createApiManager({ callback, onError?, hydrationIntervalInMs? }) => Promise<{ startHydration, stopHydration, useApi, abort, cleanup }>

  • callback: (abortSignal: AbortSignal) => T | Promise

    • Called to obtain the auth/credential data. Called once during manager creation and again when the cache is empty or a re-hydration/refresh is needed.
    • Receives an AbortSignal so you can cancel any network requests.
  • onError?: (error: any) => boolean | Promise

    • Called when a useApi callback throws. Should return true to reattempt the call after refreshing credentials, or false to rethrow the original error.
    • If not provided, the manager defaults to reattempting on error.
  • hydrationIntervalInMs?: number

    • If provided, the manager will periodically call callback and refresh the cached auth data.

Returned helpers

  • useApi(useApiCallback: (authData: T, abortSignal: AbortSignal) => Promise | R): Promise

    • Use this to perform API calls that depend on the auth data. If the call throws, onError determines whether the manager should refresh credentials and retry once.
  • startHydration(): void

    • Start the periodic refresh (requires hydrationIntervalInMs to be set).
  • stopHydration(): void

    • Stop the periodic refresh.
  • abort(): void

    • Abort current in-flight requests and create a fresh internal AbortController.
  • cleanup(): void

    • Convenience to stop hydration and abort in-flight requests.

Behavior notes and edge cases

  • Initial callback invocation: createApiManager calls your callback once during setup to populate the cached auth data. If it throws, the error will bubble up.

  • Default onError behavior: If onError is not provided, the manager will reattempt a failed useApi call once by refreshing credentials. Provide onError to customize this behavior.

  • Aborting: The manager exposes abort() to cancel current in-flight requests. The internal AbortController is replaced after aborting so future calls get a fresh signal.

  • Hydration: Use hydrationIntervalInMs for periodic refresh (for example to refresh short-lived tokens). Hydration errors are caught and logged; they don't throw.

Quick patterns

  • Refresh-only on-demand (no hydration): call useApi, rely on onError to return true so failed calls are retried after refresh.

  • Scheduled refresh: pass hydrationIntervalInMs to keep the auth data fresh in the background.

Testing tips

  • Keep callback small and easy to stub in tests; e.g. return a static token string or an in-memory rotating value.
  • Test onError behavior by making useApi throw once and assert that the callback is called again before retry.

License

MIT

Contributions

PRs welcome — keep changes small and add tests where applicable.