Onjsdev Logo
Axios Instance | axios.create
12 Jun 20254 min read
Web DevelopmentJavaScriptNodeJSAxiosReactJS

Axios Instance | axios.create


When you first add Axios to your project, you get a very basic setup for making HTTP requests. But there’s a catch — every time you make a request, you have to manually configure things like headers, timeouts, and base URLs. Doing this over and over, especially when dealing with multiple APIs, quickly becomes repetitive and error-prone. 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 your HTTP requests with pre-configured settings, so you don’t have to repeat yourself every time you make a request.

Using an instance, you can set default values for your request settings such as headers, authentication tokens, base URLs, and request and response interceptors. This also centralizes your HTTP requests and makes it easier to work with your 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 your default request configurations to this method.

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

Here, we have two different custom Axios instances(api1 and api2) with respective configurations for making HTTP requests to different APIs. Whichever instance we send a request through, those configurations will be applied to that request.

Now, let's see them in action.

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

Since Axios instances automatically inherit base URL, timeout, and header values set during creation, you only need to provide the specific URL.

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

Unlike the get method, you can provide any additional data required for your post request.

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);
  });

How To Override Axios Instance Configurations

In some scenarios, you may need to override the predefined settings on a per-request basis, which can be easily achieved by passing a configuration object as the second argument to your request method.

// 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 overrode the default request header values by providing a new header object for the 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 believe the best way to make HTTP requests with Axios is to create separate instances for each API you work with. This approach allows you to easily centralize and manage configurations specific to each API.

Thank you for reading