Onjsdev

Share


Axios Instance | Axios.create Method


By onjsdev

May 6th, 2024

When you first add Axios to your project, you get a very basic setup for making HTTP requests. The problem with this setup is that you need to repeatedly configure it to set request configurations such as headers, timeouts, and base URLs for each API call, which becomes tedious quickly, 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, eliminating the need to repeatedly configure request settings for each API call.

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

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

How To Create An Axios Instance

An Axios instance is created with the axios.create() method. You can easily pass the default configurations to this method for your API calls.

Here is an 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
  },
});

As you can see above, we have two different custom Axios instances with respective configurations for making HTTP requests to different APIs. Whichever API instance we send a request through, these configurations will be applied 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.

Here are examples for two different request types.

Get Request

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

Post Request

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 above, we didn't specify any base URLs, timeouts, or headers values for the requests because the Axios instances automatically assign them the values we specify when creating the instances. Therefore, you only need to provide the relevant URL and additional data if it is required.

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