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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@pavansapkale/x-fetch

v1.0.1

Published

A lightweight, type-safe wrapper around the native Fetch API for frontend projects.

Readme

x-fetch

A lightweight, type-safe wrapper around the native Fetch API for frontend projects.

Features

  • 🚀 Lightweight: Minimal overhead over native fetch.
  • 🔒 Type-Safe: Built with TypeScript for excellent developer experience.
  • 🛠 Configurable: Support for baseURL, default headers, and more.
  • 🔌 Interceptors: (Coming Soon) Hooks for request and response manipulation.
  • 📦 ESM & CJS: Dual build support for modern and legacy environments.

Installation

npm install x-fetch
# or
yarn add x-fetch
# or
pnpm add x-fetch

Usage

Basic Usage

Use the global xFetch instance for quick requests.

import { xFetch } from 'x-fetch';

// GET Request
const [data, error] = await xFetch.get('/api/users');
if (error) return console.error(error);
console.log(data);

// POST Request
const newUser = { name: 'John Doe', email: '[email protected]' };
const [response, err] = await xFetch.post('/api/users', newUser);

Custom Instance

Create a custom instance to set a baseURL or default options.

import { XFetch } from 'x-fetch';

const api = new XFetch({
  baseURL: 'https://api.example.com/v1',
  headers: {
    'Authorization': 'Bearer token',
  },
});

// Requests will be relative to baseURL
const [users, error] = await api.get('/users');

TypeScript Support

You can define the expected response type for better type safety.

interface User {
  id: number;
  name: string;
}

const [user, error] = await xFetch.get<User>('/users/1');
if (user) {
    console.log(user.name);
}

Advanced Usage

Timeout

Set a timeout in milliseconds. The request will be aborted if it takes longer than the specified time.

try {
  const data = await xFetch.get('/long-running-task', { timeout: 5000 });
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request timed out');
  }
}

Retry Mechanism

Configure automatic retries for failed requests.

const data = await xFetch.get('/unstable-api', {
  retry: {
    retries: 3,        // Number of retries
    retryDelay: 1000,  // Delay between retries in ms
    retryOn: [500, 503] // HTTP status codes to retry on (default: 5xx if not specified)
  }
});

Interceptors

Intercept requests and responses to inject headers, log data, or handle errors globally.

const api = new XFetch({
  baseURL: 'https://api.example.com',
  interceptors: {
    request: async (config) => {
      // Add auth token
      const token = localStorage.getItem('token');
      if (token) {
        config.headers = { ...config.headers, Authorization: `Bearer ${token}` };
      }
      console.log('Requesting:', config.url);
      return config;
    },
    response: async (response) => {
      console.log('Response status:', response.status);
      return response;
    },
    error: (error) => {
      console.error('Global error handler:', error);
      throw error;
    }
  }
});

Query Parameters

Automatically serialize query parameters.

// GET /users?page=1&sort=asc&tags=a&tags=b
await xFetch.get('/users', {
  params: {
    page: 1,
    sort: 'asc',
    tags: ['a', 'b']
  }
});

Response Types

Specify the expected response type.

// Get an image as a Blob
const imageBlob = await xFetch.get('/avatar.png', { responseType: 'blob' });

Error Handling

x-fetch returns a tuple [data, error]. You don't need try-catch blocks!

const [data, error] = await xFetch.get('/api/protected');

if (error) {
  console.error(`Error ${error.status}: ${error.statusText}`);
  console.error('Response Body:', error.data);
  return;
}

// data is safe to use here
console.log(data);

Caching

Cache responses in memory or local storage with TTL support.

// Cache for 5 minutes in memory
await xFetch.get('/api/config', { 
  cache: { 
    ttl: 5 * 60 * 1000,
    storage: 'memory' // or 'localStorage', 'sessionStorage'
  } 
});

// Force update (ignore cache)
await xFetch.get('/api/config', { 
  cache: { 
    ttl: 5 * 60 * 1000,
    forceUpdate: true 
  } 
});

API

new XFetch(options)

Creates a new instance of XFetch.

  • options.baseURL (string): Base URL for all requests.
  • options.timeout (number): Default timeout in milliseconds.
  • options.retry (RetryConfig): Default retry configuration.
  • options.cache (CacheConfig): Default cache configuration.
  • options.responseType (ResponseType): Default response type ('json', 'text', 'blob', etc.).
  • options.headers (HeadersInit): Default headers to include in every request.
  • options.interceptors (object):
    • request: Function to modify config before request.
    • response: Function to handle response before returning.
    • error: Function to handle errors globally.

Methods

  • get<T>(url, options): Performs a GET request.
  • post<T>(url, data, options): Performs a POST request.
  • put<T>(url, data, options): Performs a PUT request.
  • patch<T>(url, data, options): Performs a PATCH request.
  • delete<T>(url, options): Performs a DELETE request.
  • head<T>(url, options): Performs a HEAD request.
  • options<T>(url, options): Performs an OPTIONS request.
  • request<T>(url, options): Generic request method.

License

ISC