Axios Instance

Axios Instance

Axios is a popular JavaScript library used for making HTTP requests. It is widely used in web development to fetch data from servers and interact with APIs. One powerful feature of Axios is the ability to create and use instances, which can provide more flexibility and organization in your code. In this beginner’s guide, we will explore what Axios instances are, why they are useful, and how to use them effectively.

What is Axios?

Axios is a promise-based HTTP client for the browser and Node.js. It is designed to handle HTTP requests and responses in a simple and efficient way. Axios supports a wide range of features, including making GET and POST requests, handling request and response headers, and automatically transforming data.

One of the key advantages of Axios is its ease of use and the ability to work seamlessly with promises. It allows developers to write clean and concise code for making asynchronous HTTP requests, making it a popular choice in modern web development.

Why Use Axios Instances?

Axios instances provide a way to create a base configuration for your HTTP requests. Instead of repeating the same configuration for every request, you can create an instance with default settings. This can be particularly useful in scenarios where multiple requests share common characteristics, such as a common base URL or headers.

Here are some reasons why using Axios instances is beneficial:

  1. Code Organization: Axios instances allow you to centralize the configuration for your HTTP requests. This makes your code more organized and easier to maintain. You can set default values for headers, base URLs, and other configurations in one place.
  2. Default Configurations: You can set default configurations for your Axios instance, such as default headers, timeout values, and response types. This reduces the need to duplicate these settings in every request.
  3. Interceptors: Axios instances support interceptors, which are functions that can be executed before a request is sent or after a response is received. This allows you to globally handle request and response logic, such as adding authentication tokens, logging, or error handling.
  4. Multiple Instances: In some applications, you may need to interact with multiple APIs or endpoints. Creating separate Axios instances for each API or endpoint allows you to manage them independently, with different configurations as needed.

Now, let’s dive into how to create and use Axios instances in your projects.

Creating an Axios Instance

Creating an Axios instance is a straightforward process. You start by importing the Axios library and then using the create method to create an instance. Here’s an example:

// Import Axios library
import axios from 'axios';

// Create an Axios instance
const apiInstance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000, // milliseconds
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
});

// Now, apiInstance is a configured Axios instance

In the example above, we’ve created an Axios instance named apiInstance. This instance has a base URL of https://api.example.com, a timeout of 5000 milliseconds, and default headers including an authorization token.

Making Requests with Axios Instances

Once you have created an Axios instance, you can use it to make HTTP requests in a way that inherits its configurations. Here’s how you can make a simple GET request using the apiInstance we created:

// Making a GET request using the Axios instance
apiInstance.get('/posts')
  .then(response => {
    // Handle successful response
    console.log('Response:', response.data);
  })
  .catch(error => {
    // Handle error
    console.error('Error:', error);
  });

In the example above, the get method is called on the apiInstance with the relative URL /posts. The request inherits the base URL, timeout, and headers from the instance. The response is handled in the promise’s then block, and any errors are caught in the catch block.

Default Configurations and Headers

Axios instances allow you to set default configurations that apply to all requests made with that instance. Let’s explore how you can set default headers and other configurations:

// Create an Axios instance with default configurations
const apiInstance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
});

// Set default headers for the instance
apiInstance.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In this example, we added an additional default header (X-Requested-With) to the Axios instance. This header will be included in every request made with apiInstance.

Interceptors

Interceptors in Axios are functions that can be executed before a request is sent or after a response is received. This is a powerful feature that allows you to globally handle various aspects of your HTTP requests.

Here’s an example of using interceptors with an Axios instance:

// Create an Axios instance with interceptors
const apiInstance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
});

// Request interceptor
apiInstance.interceptors.request.use(
  config => {
    // Do something before sending the request
    console.log('Request Interceptor:', config);
    return config;
  },
  error => {
    // Handle request error
    console.error('Request Error Interceptor:', error);
    return Promise.reject(error);
  }
);

// Response interceptor
apiInstance.interceptors.response.use(
  response => {
    // Do something with the response data
    console.log('Response Interceptor:', response.data);
    return response;
  },
  error => {
    // Handle response error
    console.error('Response Error Interceptor:', error);
    return Promise.reject(error);
  }
);

In this example, we’ve added both a request interceptor and a response interceptor to the apiInstance. The request interceptor logs information about the request before it is sent, and the response interceptor logs information about the response before it is processed.

Multiple Axios Instances

In some projects, you may need to interact with multiple APIs or endpoints, each with its own configuration. Axios makes it easy to create multiple instances for such scenarios.

// Create multiple Axios instances
const apiInstance1 = axios.create({
  baseURL: 'https://api.example.com/v1',
});

const apiInstance2 = axios.create({
  baseURL: 'https://api.example.com/v2',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ANOTHER_ACCESS_TOKEN',
  },
});

// Use the instances to make requests
apiInstance1.get('/posts')
  .then(response => {
    console.log('Response from API v1:', response.data);
  })
  .catch(error => {
    console.error('Error from API v1:', error);
  });

apiInstance2.get('/users')
  .then(response => {
    console.log('Response from API v2:', response.data);
  })
  .catch(error => {
    console.error('Error from API v2:', error);
  });

In this example, we’ve created two Axios instances, apiInstance1 and apiInstance2, each with its own base URL and headers. This allows you to manage and configure each instance independently.

Conclusion

Axios instances are a powerful feature that can greatly enhance the organization and maintainability of your code when working with HTTP requests. By creating instances with default configurations, you can avoid duplicating code and ensure consistent behavior across your requests. Interceptors further extend the capabilities, allowing you to globally handle request and response logic.

As you continue to work with Axios, exploring additional features and best practices will help you become proficient in handling various scenarios. Whether you are building a simple web application or a complex system, Axios instances provide a valuable tool for managing your HTTP interactions effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top