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

ts-rest-api

v1.1.6

Published

A flexible and powerful TypeScript HTTP client with middleware support for making API requests

Readme

ts-rest-api

npm version License: ISC

A flexible and powerful HTTP client built with TypeScript that provides advanced features for making API requests with middleware support.

Features

  • 🌐 Full TypeScript Support: Strongly typed API for enhanced developer experience
  • 🔄 Middleware Architecture: Easily extend and customize request processing
  • 🔌 URL Composition: Simple path and query parameter handling
  • 📦 Response Formatting: Automatic handling of different response types (JSON, Blob, Text)
  • 🔒 Authentication: Built-in token-based authentication support
  • 🧩 Next.js Integration: Ready-to-use middleware for Next.js applications
  • 📱 Browser Utilities: Includes browser-specific features like file downloads

Installation

# npm
npm install ts-rest-api

# yarn
yarn add ts-rest-api

# pnpm
pnpm add ts-rest-api

Basic Usage

import {ApiClient} from 'ts-rest-api';

// Create a custom client instance with base URL and optional token
const api = new ApiClient('https://api.example.com', 'initial-token');

// Later update token if needed
api.setToken('updated-token');

// Make requests
const response = await api.post<CreateUserResponse>({
    path: 'users',
    body: {name: 'John Doe', email: '[email protected]'}
});

Middleware Support

TSFetch allows you to extend functionality through middleware:

import {ApiClient, ApiMiddleware} from 'ts-rest-api';

// Create a custom middleware
const loggingMiddleware: ApiMiddleware = (options) => {
    console.log('Request:', options);
    return options;
};

// Create a client and add middleware
const api = new ApiClient('https://api.example.com');
api.use(loggingMiddleware);

// Chain middleware
api.use((options) => {
    // Add custom headers
    return {
        ...options,
        headers: {
            ...options.headers,
            'X-Custom-Header': 'custom-value'
        }
    };
});

Next.js Integration

TSFetch includes a middleware specifically for Next.js applications that enables per-user cache handling with tags and revalidation:

import { ApiClient, nextJsPerUserCachingMiddleware } from 'ts-rest-api';

// Create a client with Next.js support
const api = new ApiClient('https://api.example.com');
api.use(nextJsPerUserCachingMiddleware);

// Use with Next.js cache options
const data = await api.get<UserData>({
  path: 'users/profile',
  next: {
    revalidate: 60, // Cache for 60 seconds
    tags: ['user-profile'], // Add custom cache tag
    cache: 'force-cache' // Cache strategy
  }
});

// Fetch with no caching
const latestData = await api.get<UserData>({
  path: 'users/profile',
  next: {
    cache: 'no-store' // Disable caching
  }
});

The middleware automatically generates unique cache keys based on the URL and authentication token, ensuring proper cache isolation between users and cache invalidation when auth state changes.

API Methods

TSFetch supports all standard HTTP methods:

// GET request
const data = await api.get<ResponseType>({
    path: 'resource',
    params: ['param1', 'param2'],  // Will be appended as /resource/param1/param2
    query: {sort: 'name', filter: 'active'}  // Will be added as ?sort=name&filter=active
});

// POST request with body
const result = await api.post<ResponseType>({
    path: 'resource',
    body: {name: 'New Item'}
});

// Other methods
await api.put({path: 'resource/123', body: {name: 'Updated Item'}});
await api.patch({path: 'resource/123', body: {status: 'active'}});
await api.delete({path: 'resource/123'});

Browser Utilities

TSFetch includes utilities for browser-specific operations:

// Download a file
await api.browserOnly.downloadFile({
    url: 'https://example.com/files/document.pdf',
    filename: 'document.pdf'
});

Advanced Usage

Custom Request Options

const response = await api.get({
    path: 'resources',
    options: {
        credentials: 'include',
        cache: 'no-cache',
        headers: {
            'Accept-Language': 'en-US'
        }
    }
});

Working with FormData

const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('name', 'My Document');

const result = await api.post({
    path: 'upload',
    body: formData,
    options: {
        headers: {
            // Content-Type is automatically set by the browser for FormData
        }
    }
});

Handling Errors

try {
    const data = await api.get({path: 'resources'});
    // Process successful response
} catch (error) {
    console.error('API request failed:', error);
    // Handle error appropriately
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the ISC License - see the LICENSE file for details.

Author

Vitalii Shevchuk