DEV Community

Cover image for Migrate to xior from axios
suhaotian
suhaotian

Posted on

Migrate to xior from axios

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 ✅ Support by third library Browser: XMLHttpRequest; Node: http module
xior xior size ✅ Built-in support Both use fetch

Getting Started

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

Installing

# npm
npm install xior

# pnpm
pnpm add xior

# bun
bun add xior

# yarn
yarn add xior
Enter fullscreen mode Exit fullscreen mode

GET method

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
  });
Enter fullscreen mode Exit fullscreen mode

POST method

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
  });
Enter fullscreen mode Exit fullscreen mode

Creating instance

import axios from 'xior';

const http = axios.create({ baseURL: 'https://example.com/' });
Enter fullscreen mode Exit fullscreen mode

Inteceptors

Request interceptors:

import axios from 'xior';

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

Response interceptors:

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);
  }
);
Enter fullscreen mode Exit fullscreen mode

Plugins

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

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

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}%`);
  // },
});
Enter fullscreen mode Exit fullscreen mode

Custom your own plugin:

xior let you easily to create custom plugins.

Here are some examples:

  1. Simple Logging plugin:
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;
  };
});
Enter fullscreen mode Exit fullscreen mode

More details, check xior on npm

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

Top comments (0)