Understanding Axios Instance in JavaScript

3 min read

Axios is a popular JavaScript library used for making HTTP requests from a web browser or Nodejs environment. It provides an easy-to-use and powerful interface for handling HTTP communication with servers.

In this article, we will dive deep into the concept of Axios instances that simplifies the configuration and explore its practical examples.

What is Axios Instance?

In Axios, an instance is an independent object that allows you to define default configurations for HTTP requests. Instead of setting configuration options repeatedly for each request. By creating an Axios instance, you can make HTTP request with pre-configured settings.

When you create an Axios instance, you can set default values for headers, authentication tokens, base URLs, request interceptors, response interceptors, and more. This makes it easy to centralize and manage these configurations.

Creating an Axios Instance

Creating an Axios instance is straightforward. To do so, you need to use the axios.create() method, which returns 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
const instance = 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
  },
});

In this example, we created an Axios instance with a base URL, a default timeout of 5 seconds, and a default content type of JSON.

Using Axios Instance for Requests

Once you have created an Axios instance, you can use it to send HTTP requests using familiar methods like get, post, put, delete, etc. The instance will inherit the default configuration values set during its creation

Let’s see how you can use the instance to make HTTP requests.

Get Request

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

Post Request

instance.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.

Overriding 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.

// Override instance configuration for a specific request
instance.get('/products', {
  params: {
    category: 'electronics',
  },
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

In this example, we override the Axios instance’s base URL by providing the params object for the get request.

Interceptors and Global Error Handling

Another advantage of using Axios instances is the ability to add interceptors for requests and responses. Interceptors are functions that can be executed before a request is sent or after a response is received.

// Adding request interceptor
instance.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
instance.interceptors.response.use((response) => {
  // Modify the response data here
  return response;
}, (error) => {
  // Handle global errors here
  return Promise.reject(error);
});

In this example, we added request and response interceptors to the Axios instance. The request interceptor allows you to modify the request configuration, while the response interceptor allows you to handle and modify the response data.

Conclusion

Axios instances are a powerful feature that simplifies the process of making HTTP requests in JavaScript applications. By creating instances with default configurations, you can centralize and organize the settings for all your API calls.

Thank you for reading