DEV Community

Cover image for Exploring the Depths of Axios: Uncovering Lesser-Known Capabilities
Shreeyash SJ
Shreeyash SJ

Posted on

Exploring the Depths of Axios: Uncovering Lesser-Known Capabilities

Exploring the Depths of Axios: Uncovering Lesser-Known Capabilities

As one of the most popular HTTP client libraries in the JavaScript ecosystem, Axios is renowned for its simplicity, flexibility, and powerful feature set. While many developers are familiar with its basic functionalities, there are several lesser-known features that remain untapped. In this article, we’ll take a deep dive into some of these hidden gems, helping Axios users unlock new capabilities and improve their HTTP request handling workflows.

1. Custom Instance Configuration

Imagine you’re developing a multi-environment application that interacts with different API servers. With Axios’s custom instance configuration, you can easily manage these environments by creating custom instances with specific configurations for each environment. For instance, you can set different base URLs or headers depending on whether you’re working on a development, staging, or production environment.

// Creating a custom Axios instance with specific configuration
import axios from 'axios';

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

export default customAxios;
Enter fullscreen mode Exit fullscreen mode

By leveraging custom instances, developers can maintain cleaner code organisation and achieve greater flexibility in managing their HTTP requests.

2.Interceptors

Suppose you’re building an authentication system for your application. With Axios interceptors, you can seamlessly intercept outgoing requests to add authentication headers before they’re sent to the server. Similarly, you can intercept incoming responses to handle authentication errors and redirect users to the login page if their session expires. Interceptors are powerful middleware functions that allow users to intercept requests or responses before they are handled by Axios.

// Adding request interceptor
axios.interceptors.request.use(
  (config) => {
    // Add custom logic before sending the request
    console.log('Request interceptor triggered:', config);
    return config;
  },
  (error) => {
    // Handle request error
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// Adding response interceptor
axios.interceptors.response.use(
  (response) => {
    // Add custom logic after receiving the response
    console.log('Response interceptor triggered:', response);
    return response;
  },
  (error) => {
    // Handle response error
    console.error('Response error:', error);
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

With interceptors, developers can implement cross-cutting concerns in a centralized manner, improving code maintainability and reducing duplication.

3. Handling Request Cancellation

Imagine you’re developing a real-time chat application where users can send and receive messages. If a user navigates away from the chat screen while a message is being sent, you don’t want to waste network resources by continuing to send the message. By leveraging Axios’s request cancellation feature, you can cancel the pending request when the user navigates away, ensuring efficient resource utilisation. This feature is particularly valuable in scenarios where users navigate away from a page or perform actions that render ongoing requests obsolete.

// Importing Axios library and cancellation token
import axios, { CancelToken } from 'axios';

// Creating a cancellation token
const source = CancelToken.source();

// Making a request with cancellation token
axios.get('/api/data', {
  cancelToken: source.token
}).then((response) => {
  console.log('Response:', response.data);
}).catch((error) => {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  } else {
    console.error('Request error:', error);
  }
});

// Canceling the request
source.cancel('Request canceled by the user');
Enter fullscreen mode Exit fullscreen mode

By incorporating request cancellation into their applications, developers can enhance the user experience and optimise resource utilisation.

4. Global Error Handling

Suppose you’re working on an e-commerce application where users frequently encounter network errors or server timeouts. With Axios’s global error handling feature, you can define a centralized error handling logic to gracefully handle these errors. For example, you can display a friendly error message to the user, retry the failed request, or log the error for further analysis.

// Adding global error handling interceptor
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      // The request was made and the server responded with a status code
      console.error('Response error:', error.response.status, error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an error
      console.error('Error:', error.message);
    }
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

With global error handling, developers can ensure consistent error reporting and gracefully handle unexpected situations in their applications.

Conclusion

In conclusion, Axios offers a wealth of features beyond its basic functionalities, providing users with powerful tools to streamline their HTTP request handling workflows. By exploring these lesser-known features, developers can unlock new capabilities, improve code quality, and enhance the reliability and performance of their applications. Whether it’s creating custom instances, implementing interceptors, handling request cancellation, or managing errors, Axios empowers users to tackle diverse challenges with ease. Let’s continue to explore and leverage the full potential of this versatile library in our projects.

If you found this article helpful, please consider giving it a like and sharing it.

Top comments (0)