Onjsdev Logo
What is an Axios Instance? | Axios.create()
25 Jun 20255 min read
AxiosAxios InstanceAxios.createAxios default timeoutCreate an Axios instanceJavaScriptNodeJSReactJSVueJSFetch APIAxios Instance Example

What is an Axios Instance? | Axios.create()


When you first add Axios to your project, you get a basic setup for making HTTP requests right away. But there’s a catch — every time you make a request, you have to manually configure request settings 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 Axios instances come into play.

What is an Axios Instance?

An Axios instance, actually, is a customized version of the Axios client. Creating an Axios instance allows you to make your HTTP requests with pre-configured options, so you don’t have to repeat yourself every time you make a request.

Header, authentication tokens, base URL, query params, timeout are some of the options that you can set for your Axios instance. Because you can manage these settings from one place, your HTTP requests are also centralized, making it easier to work with your APIs.

How To Create An Axios Instance

You can create a custom Axios instance using the axios.create() method. Just pass in an object with your default request configurations and it will return a new instance that uses those configurations for every request.

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

In this example, we’ve created two separate Axios instances—api1 and api2—each with its own configuration. This lets you send requests to different APIs using different settings.

When you make a request with one of these instances, it automatically applies the configuration you set for that specific instance.

Now, let's see them in practice.

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, PUT, DELETE, etc.

Here are examples for the GET and POST request methods.

Get Request

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

api1
  .get("/users")
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Additionally, as the nature of the post method, you can provide any additional data required for your 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 an Axios Instance

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

This example shows how to override the default request header values:

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

Axios Instance With Interceptors

Another advantage of using Axios instances is the ability to add interceptors for requests and responses. Interceptors in Axios are functions that can be executed just before a request is sent or after a response is received. For example, whenever a response is received, you can transform the response data or handle errors.

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

Axios instance vs Axios Request Config Defaults

If you are familiar with Axios request configuration defaults, you may have noticed that they are similar to Axios instances 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";

On the other hand, requests made with axios instance are only applied to the request made with that instance. That is, Axios instances allow you to encapsulate default configurations for a specific part of your application, meaning you can create various instances with different configurations for different purposes.

FAQ

Is it possible to share one Axios instance across multiple files?

Absolutely. Just export your instance (api.js) and import it wherever needed in your app. This keeps config centralized and consistent.

What are some good naming conventions for multiple Axios instances?

Use names that reflect their API purpose, like authApi, userApi, or adminApi to clarify intent and keep your imports readable.

Where should I create my Axios instance in a React project?

Ideally in a separate file like `api.js` or `axios.js` under a `/lib` or `/services` folder. This keeps the config modular and reusable across components and hooks.

Can I replicate Axios instance features using Fetch?

Yes, but you'll have to build your own wrapper around fetch to handle base URLs, headers, token injection, and error formatting. It takes more effort but is doable.

Do Axios instances support all Axios features?

Yes. Axios instances support all the core features of Axios, including interceptors, cancel tokens, timeout settings, and response transformations.

Conclusion

Staying organized is essential when building any application—and JavaScript is no exception. Making HTTP requests is one of the most common tasks in JavaScript apps, and using Axios instances is a great way to keep your code well-structured.

Thank you for reading!