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

@rocketbase/commons-rest-client

v1.2.0

Published

Runtime library for @rocketbase OpenAPI generated TypeScript clients

Readme

@rocketbase/commons-rest-client

Runtime library for TypeScript clients generated by the @rocketbase OpenAPI generator.

Features

  • 🔐 Authentication: React Context-based auth with Bearer token interceptor
  • 🌐 Multi-Client Support: Named base URLs for multiple API endpoints
  • 📄 Pagination: Helpers for React Query infinite queries
  • 🎯 Type-Safe: Full TypeScript support with strict typing
  • 📦 Tree-Shakeable: ESM and CJS builds with minimal bundle size
  • Modern: Built for axios 1.7+, React 18+, TypeScript 5+

Installation

npm install @rocketbase/commons-rest-client axios react

Peer Dependencies

  • axios >= 1.7.0
  • react >= 18.0.0

Usage

Basic Setup (Single API)

import { AuthProvider, type TokenService } from '@rocketbase/commons-rest-client';

// Implement your token service
const tokenService: TokenService = {
  isLoggedIn: () => !!localStorage.getItem('token'),
  token: () => localStorage.getItem('token'),
  updateToken: async () => {
    // Optional: refresh token logic
    const newToken = await refreshToken();
    localStorage.setItem('token', newToken);
    return newToken;
  },
};

// Wrap your app
function App() {
  return (
    <AuthProvider
      tokenService={tokenService}
      baseUrl="https://api.example.com"
    >
      <YourApp />
    </AuthProvider>
  );
}

Multi-Client Setup (Multiple APIs)

import { AuthProvider } from '@rocketbase/commons-rest-client';

function App() {
  return (
    <AuthProvider
      tokenService={tokenService}
      baseUrl={{
        main: 'https://api.example.com',
        auth: 'https://auth.example.com',
        analytics: 'https://analytics.example.com',
      }}
    >
      <YourApp />
    </AuthProvider>
  );
}

Using Generated Clients

import { useAuth } from '@rocketbase/commons-rest-client';
import { createMainApi, createAuthApi } from './generated/client';

function MyComponent() {
  const { axiosClient, baseUrl } = useAuth();

  // Single API
  const api = createMainApi(axiosClient, { baseURL: baseUrl() });

  // Multiple APIs with named base URLs
  const mainApi = createMainApi(axiosClient, { baseURL: baseUrl('main') });
  const authApi = createAuthApi(axiosClient, { baseURL: baseUrl('auth') });

  // Use the API
  const data = await api.users.getUser({ id: '123' });
}

Custom Axios Configuration

<AuthProvider
  tokenService={tokenService}
  baseUrl="https://api.example.com"
  axiosConfigure={(instance) => {
    instance.defaults.timeout = 5000;
    instance.defaults.headers.common['X-Custom-Header'] = 'value';
  }}
>
  <YourApp />
</AuthProvider>

Using Pagination Utilities

import { useInfiniteQuery } from '@tanstack/react-query';
import { createPaginationOptions, infiniteTotalElements } from '@rocketbase/commons-rest-client';

function UserList() {
  const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
    queryKey: ['users'],
    queryFn: ({ pageParam = 0 }) => api.users.list({ page: pageParam, size: 20 }),
    ...createPaginationOptions(),
  });

  const totalUsers = infiniteTotalElements(data);

  return (
    <div>
      <p>Total users: {totalUsers}</p>
      {data?.pages.map((page) =>
        page.content.map((user) => <UserCard key={user.id} user={user} />)
      )}
      {hasNextPage && <button onClick={() => fetchNextPage()}>Load More</button>}
    </div>
  );
}

API Reference

AuthProvider

React component that provides authentication context.

Props:

  • tokenService: TokenService - Token service implementation
  • baseUrl: string | Record<string, string> - API base URL(s)
  • axiosConfigure?: (instance: AxiosInstance) => void - Optional axios configuration
  • children: ReactNode - Child components

useAuth()

Hook to access authentication context. Must be used within AuthProvider.

Returns:

  • axiosClient: AxiosInstance - Configured axios instance with auth interceptor
  • baseUrl: (key?: string) => string - Base URL resolver
  • tokenService: TokenService - Token service instance

TokenService

Interface for managing authentication tokens.

interface TokenService {
  isLoggedIn: () => boolean;
  token: () => string | null;
  updateToken?: () => Promise<string>;
}

PageableResult

Standard pageable result wrapper for REST APIs.

interface PageableResult<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  page: number;
  pageSize: number;
}

createPaginationOptions()

Creates pagination options for React Query infinite queries.

Returns:

  • getPreviousPageParam - Function to get previous page number
  • getNextPageParam - Function to get next page number
  • initialPageParam - Initial page number (0)

infiniteTotalElements(data)

Extracts total element count from infinite query data.

Parameters:

  • data: InfiniteData<PageableResult<T>> | undefined - React Query infinite data

Returns: number - Total number of elements across all pages

buildRequestorFactory()

Creates a requestor factory for building type-safe API client functions.

const builder = buildRequestorFactory(axiosClient, { baseURL: 'https://api.example.com' });

const getUser = builder<{ id: string }, User>({
  method: 'get',
  url: ({ id }) => `/users/${id}`,
});

const user = await getUser({ id: '123' });

Development

Build

cd typescript-runtime
npm install
npm run build

Output files:

  • dist/index.mjs - ESM build
  • dist/index.cjs - CommonJS build
  • dist/index.d.ts - TypeScript type definitions

Testing

npm run test

Type Checking

npm run typecheck

License

MIT

Author

rocketbase.io