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 🙏

© 2024 – Pkg Stats / Ryan Hefner

fetch-ax

v2.0.0

Published

A modern HTTP client that extends the Fetch API, providing Axios-like syntax and full compatibility with Next.js App Router.

Downloads

707

Readme

Features

  • "Don't learn, only use"
  • Zero learning curve, Zero configuration, Zero dependencies
  • Fully compatible with Next.js App Router
  • Simple yet powerful

Why fetch-ax?

We are usually familiar with using API libraries (e.g., axios), but sometimes we need to use the native web Fetch API. This situation has become more frequent with the introduction of Next.js v13 App Router. Next.js has extended the basic Fetch API to add important features like server-side caching. As a result, Fetch has become a necessity rather than an option.

Fetch is a powerful API, but it lacks key features for enhancing developer experience (DX), such as interceptors, instance, error handling, and response parsing. The absence of these can significantly reduce productivity and complicate code. While some libraries have extended fetch to address these issues, they often introduce unique syntax, creating a new learning curve.

We no longer need to learn how to use additional API libraries. Instead, we can develop efficiently using the familiar Axios syntax. fetch-ax extends Fetch with syntax similar to Axios, providing all the utility functions essential for modern application development, such as interceptors, error handling, and response parsing.

Examples

Performing a GET request

import fetchAX from 'fetch-ax';

fetchAX
  .get('https://example.com/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

fetchAX
  .get('https://example.com/user', {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// async/await
async function getUser() {
  try {
    const response = await fetchAX.get('https://example.com/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Performing a POST request

fetchAX
  .post('https://example.com/user', {
    firstName: 'Fred',
    lastName: 'Flintstone',
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

fetch-ax API

fetchAX,create([options])
fetchAX.get(url[, args])
fetchAX.post(url[, data[, args])
fetchAX.put(url[, data[, args])
fetchAX.patch(url[, data[, args])
fetchAX.delete(url[, args])
fetchAX.head(url[, args])

🚀Quick Start

Install:

# npm
npm i fetch-ax

# yarn
yarn add fetch-ax

#pnpm
pnpm i fetch-ax

✔️ Instance

You can create a new instance of fetchAX with a default options.

const instance = fetchAX.create({
  baseURL: 'https://example.com',
  headers: {
    Authorization: `Bearer ${YOUR_ACCESS_TOKEN}`,
  },
});

instance.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone',
});

Instance methods

The available instance methods are listed below.

fetchAX#get(url[, args])
fetchAX#post(url[, data[, args])
fetchAX#put(url[, data[, args])
fetchAX#patch(url[, data[, args])
fetchAX#delete(url[, args])
fetchAX#head(url[, args])

✔️ Parsing Response

If you set a response type, you can parse the response with that type. The default type is 'json'.

const instance = fetchAX.create();

// This does not parse the response
const response = instance.get('/');

// response data type is json
const responseWithJson = instance.get('/', {
  responseType: 'json',
});

// response data type is form data
const responseWithFormData = instance.get('/', {
  responseType: 'formdata',
});

✔️ Error handling

If throwError is set to true, throw an error when the status falls out of the 2XX range. The default value is true.

import fetchAX from '../src';

const instance = fetchAX.create({ throwError: true });

// error handling will not apply
const errorHandlingFalseResponse = instance.get('/', { throwError: false });

// error handling will apply
try {
  const errorHandlingTrueResponse = instance.get('/');
} catch (error) {}

✔️ Interceptor

You can intercept requests or responses

import fetchAX, { RequestInit } from '../src';

const instance = fetchAX.create({
  responseInterceptor: (response: any) => {
    console.log('default options response interceptor');
    return response;
  },
  requestInterceptor: (requestArg: RequestInit) => {
    console.log('default options reqeust interceptor');
    return requestArg;
  },
});

// The console is printed in the following order
/*
default options reqeust interceptor
requestInit reqeust interceptor
default options response interceptor
requestInit response interceptor
 */
const response = instance.get('/', {
  requestInterceptor: (requestArg: RequestInit) => {
    console.log('requestInit reqeust interceptor');
    return requestArg;
  },
  responseInterceptor: (response: any) => {
    console.log('requestInit response interceptor');
    return response;
  },
});

console.log(response);

You can also intercept responses when rejected to handle errors. This allows you to implement custom error handling logic for failed requests.

const instance = fetchAX.create({
  throwError: true,
  responseRejectedInterceptor: (error: FetchAxError) => {
    if (error.statusCode === 400) {
      return Promise.reject(
        new BadRequestError({
          message: 'Bad Request',
          response: error.response,
        }),
      );
    }
  },
});

default options

| Property | Description | Type | Default | | --------------------------- | ---------------------------------------- | ----------------------------------------------------- | --------------------------------------------------- | | baseURL | base url | string | URL | - | | headers | fetch headers | HeadersInit | new Headers([['Content-Type', 'application/json']]) | | throwError | whether to throw an error | boolean | true | | responseType | response type to parse | ResponseType | json | | responseInterceptor | interceptor to be executed on response | (response: Response) => Response | Promise | - | | responseRejectedInterceptor | interceptor to handle rejected responses | (error: any) => any | - | | requestInterceptor | interceptor to be executed on request | (requestArg: RequestInit) => RequestInit | - |