Onjsdev

Share


Axios Instance | Axios.create Method


By onjsdev

Jan 8th, 2024

When you first add Axios to your project, you get a basic setup for making HTTP requests and you need to repeatedly set headers, timeouts, and base URLs for your each API call. However this gets tedious fast, especially with multiple APIs.

This is where custom Axios instances come into play.

What is an Axios Instance?

An Axios instance is a customized version of the Axios client. Creating an Axios instance allows you to make HTTP requests with pre-configured settings.

For example, you can set default values for headers, authentication tokens, base URLs, request and response interceptors, and more in your API calls. This makes it easier to work with multiple APIs, centralize and manage HTTP requests.

Now, let's look at how to create an axios instance.

How To Create Axios Instance

With the axios.create() method, you can create a new axios instance with the specified configurations.

Let's take a look at a basic example:

// Import Axios library (Make sure you have Axios installed)
const axios = require('axios');

// Create an Axios instance for the api1
const api1 = axios.create({
  baseURL: 'https://api.example.com', // Set the base URL for all requests
  timeout: 5000, // Set the default timeout for requests to 5 seconds
  headers: {
    'Content-Type': 'application/json', // Set the default content type for requests
  },
});


// Create an Axios instance for the api2
const api2 = axios.create({
  baseURL: 'https://api2.example.com', // Set the base URL for all requests
  timeout: 3000, // Set the default timeout for requests to 5 seconds
  headers: {
    'Content-Type': 'application/json', // Set the default content type for requests
  },
});

In this example, we have created two custom Axios instances with their base URLs, default timeouts of 5 seconds, and default content types of JSON to make HTTP requests to different APIs. Whichever API instance a request is sent through, those configurations will apply to that request.

Now, let's see examples of how to use these instances to make various type of requests to different APIs.

How to Use An Axios Instance

Once you have created an Axios instance, you can use it to send HTTP requests using familiar methods like GET, POST, etc.

This way, every time we make an HTTP request to an API the default configuration values set during the instance's creation will take effect.

Here are examples for two different request types.

Get Request With Axios Instance

// Using the Axios instance for making requests
api1.get('/users')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

Post Request With Axios Instance

api2.post('/posts', {
  title: 'Hello Axios Instance',
  body: 'This is an example of using Axios instance.',
})
  .then((response) => {
    console.log('Post created:', response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

As you can see, The Axios instance handles the base URL, timeout, and default headers automatically, so you only need to provide the relative URL and additional data as required by the specific request.

How To Override Axios Instance Configurations

While Axios instances provide default configurations, you can still override them on a per-request basis by passing a configuration object as the second argument to the request method.

Here is the example:

// Override instance configuration for a specific request
api1.get('/products', {
  headers: {
  'Authorization': 'Bearer ANOTHER_ACCESS_TOKEN',
  'Custom-Header': 'Custom-Value',
};
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

In this example, we override the request header's values by providing the header object for a request.

Axios Instance With Interceptors

Another advantage of using Axios instances is the ability to add interceptors for requests and responses.

Here is the example:

// Adding request interceptor
api1.interceptors.request.use((config) => {
  // Modify the request config here (e.g., add an authorization header)
  return config;
}, (error) => {
  return Promise.reject(error);
});

// Adding response interceptor
api1.interceptors.response.use((response) => {
  // Modify the response data here
  return response;
}, (error) => {
  // Handle global errors here
  return Promise.reject(error);
});

In this example, we have added request and response interceptors to the Axios instance. Thus, we can execute commands before a request is sent or after a response is received.

For example, whenever a response is received, we can transform the response data or handle errors.

Axios instance vs Axios Request Config Defaults

Actually, in Axios, both the concept of an Axios instance and the defaults object are ways to set default configurations for your HTTP requests. However, they serve slightly different purposes.

The axios.defaults object is used to set default configurations for all Axios requests globally. Changes made to axios.defaults will affect every Axios request in your application.

// Setting global defaults for all Axios requests
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer myAccessToken';

Axios instance allows you to encapsulate default configurations for a specific part of your application, meaning you can create various instances with different configurations for different purposes.

Conclusion

I think the best way to make HTTP requests with Axios is creating instances for each APIs you work with and use them. Thus, you would easily centralize and manage configurations of each different APIs.

If you read more about Axios, then check the following articles:

Thank you for reading