Migrate to xior from axios
Tags: fetch, http, axios, cloudflare
Published: 2024-03-18 02:03:15



[**Xior**](https://github.com/suhaotian/xior) is a library based on **fetch** that supports plugins, offers an API similar to axios, and is lightweight in size.

Do you use `axios` or `fetch`?

If you are already familiar with `axios`, using `xior` will be straightforward. 

## Why xior instead of axios?

One significant reason is that axios doesn't support edge runtime and Cloudflare Worker environments.

In Cloudflare Worker or Next.js's middleware.js file, axios will throw an error: `TypeError: adapter is not a function`.

Another reason is that **xior** is more lightweight and supports plugins and if you want use modern features like fetch, xior is the best choice.

But if you need these features, axios still a better choice:

- Axios support `proxy` feature in Node.js
- Axios use `XMLHttpRequest` thats means support old browser
- Axios exists over 10 years means more stable and more features support


### Compare

| name  | Size compare                                                                                     | Plugins                   | API                                            |
| ----- | ------------------------------------------------------------------------------------------------ | ------------------------- | ---------------------------------------------- |
| axios | [![axios size](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eojftt8m24dt4rx9s3tn.png)](https://bundlephobia.com/package/axios@1.6.8) | ✅ Support by third library | Browser: `XMLHttpRequest`; Node: `http` module |
| xior  | [![xior size](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ce0nc3dmh9px3gd926h.png)](https://bundlephobia.com/package/xior@0.2.1)    | ✅ Built-in support       | Both use fetch                                 |


## Getting Started

Let's install and write some example to get started.

### Installing

```sh
# npm
npm install xior

# pnpm
pnpm add xior

# bun
bun add xior

# yarn
yarn add xior
```

### GET method

```ts
import axios from 'xior';

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

### POST method

```ts
import axios from 'xior';

axios
  .post(
    '/user',
    // body
    {
      username: 'test',
      nickname: 'j',
    },
    // options
    {
      params: {
        ID: 12345,
      },
    }
  )
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });
```

### Creating instance

```ts
import axios from 'xior';

const http = axios.create({ baseURL: 'https://example.com/' });
```

### Inteceptors

Request interceptors:

```ts
import axios from 'xior';

axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('LOGIN_TOKEN');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});
```

Response interceptors:

```ts
import axios from 'xior';

axios.interceptors.response.use(
  (result) => {
    console.log(result.status, result.data, result.config, result.resposne, result.headers);
    return result;
  },
  (error) => {
    if (error?.response?.status === 401) {
      localStorage.removeItem('LOGIN_TOKEN');
    }
    return Promise.reject(error);
  }
);
```

#### Plugins

Xior built-in many useful plugins, and let you easily custom your own plugins.

#### Plugin example, here we use download/upload progress plugin:

```ts
import axios from 'xior';
import uploadDownloadProgressPlugin from 'xior/plugins/progress';

axios.plugins.use(uploadDownloadProgressPlugin());

const formData = FormData();
formData.append('file', fileObject);
formData.append('field1', 'val1');
formData.append('field2', 'val2');

axios.post('/upload', formData, {
  // simulate upload progress to 99% in 10 seconds, default is 5 seconds
  progressDuration: 10 * 1000,
  onUploadProgress(e) {
    console.log(`Upload progress: ${e.progress}%`);
  },
  // onDownloadProgress(e) {
  //   console.log(`Download progress: ${e.progress}%`);
  // },
});
```

#### Custom your own plugin:

**xior** let you easily to create custom plugins.

Here are some examples:

1. Simple Logging plugin:

```ts
import axios from 'xior';

axios.plugins.use(function logPlugin(adapter) {
  return async (config) => {
    const start = Date.now();
    const res = await adapter(config);
    console.log('%s %s %s take %sms', config.method, config.url, res.status, Date.now() - start);
    return res;
  };
});
```

More details, check [xior on npm](https://www.npmjs.com/package/xior)


**Maybe you have issues or problem, please feel free to comment**