How to Create a Custom Axios Instance?

•

Mon Oct 31 2022

•

4 min read

Axios allows us to create new instances with custom configuration. This guide will demonstrate how to create a custom instance with Axios.

What is Axios?

There are several ways to make API calls in your applications. You can choose the built-in Fetch API or third-party libraries to call APIs. In the latter case, Axios is one of the most popular data-fetching packages available on npm.

Axios is an open-source, promise-based HTTP client. It uses JavaScript’s promises to send HTTP requests and manage their responses. Moreover, it offers additional features for fetching APIs that are not available in the basic Fetch API. Some of these features include:

  • Request interceptors.
  • Request timeouts and cancellations.
  • Custom instances.

Today, we will talk about its ability to create custom instances.

Custom Instances

Axios lets us create custom instances for API requests. Each instance is a separate client that can carry its own configuration and options like base URLs, timeouts, and headers. Then, we can reuse the configuration for API calls using the same instance.

Why are Custom Instances Used?

Most applications get their data from multiple different APIs. Each API usually requires specific options, headers, and other settings. Setting these configurations manually for each API call will result in poor, hard-to-maintain code that goes against the DRY (don’t repeat yourself) principle.

Custom instances allow us to create a separate client with a custom configuration for each API. All API calls made with that client will reuse the same configuration.

How to Create a Custom Instance Using Axios?

Let’s create a custom Axios instance. The steps to get there roughly look like this:

→ STEP #1

First, we will install and import Axios into our project. You can install Axios using a package manager like npm or yarn. Bash out the following command:

sh
npm install axios
# OR
yarn add axios

Once installed, import it into your JavaScript file using one of the following ways:

js
import axios from 'axios';
// OR
const axios = require('axios');

→ STEP #2

A regular import/require of Axios in your file creates a default Axios instance. But we need a custom instance. To create one, we can use the axios.create() function that essentially creates a new instance. It looks like this:

js
import axios from 'axios';
const NewInstance = axios.create([config]);

It accepts custom configuration as the parameter. Here you can specify things like headers, timeouts, and more. For example:

js
import axios from 'axios';
const NewInstance = axios.create({
// Configuration
baseURL: 'https://geodb-cities-graphql.p.rapidapi.com',
timeout: 8000,
headers: {
Accept: 'application/json',
'x-rapidapi-key': '<your-key-here>'
},
});

→ STEP #3

Now, it is only a matter of creating API calls with our custom instance/client. The client’s configurations will apply to all the calls. Here is an example API call made using a custom instance.

js
import axios from 'axios';
const QuotesClient = axios.create({
baseURL: 'https://famous-quotes4.p.rapidapi.com',
timeout: 8000,
headers: {
Accept: 'application/json',
'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com',
'x-rapidapi-key': '<your-key-here>',
},
});
// API Call
const getQuotes = async () => {
const response = await QuotesClient.get('/random', {
params: { category: 'all', count: '1' },
});
console.log(response.data);
};

It will result in a response close to this:

json
[
{
"id": 13190,
"text": "It takes a lot of courage to show your dreams to someone else.",
"category": "courage",
"author": "Erma Bombeck"
}
]
Loading component...

Similarly, you can use QuotesClient.post for Axios POST requests and so on. You can also create separate clients for each API and manage your application’s API calls in a better way.

Wrap Up

We hope this guide helped you learn about custom Axios instances. Check out our guides on Axios for more.