Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Debugging

API Mock

API Automated Testing

Sign up for free
Home / Tutorials / How to Handle Axios Timeout in 2024 ?

How to Handle Axios Timeout in 2024 ?

Learn how to handle axios timeout like a pro, using the best practices and tools available. Discover how to set, catch, and handle the timeout error in axios, and how to test, debug using Apidog

Have you ever faced the frustrating situation of waiting for an API response that never arrives? Or worse, getting an error message that says something like “request failed with status code 408” or “network error”? If you have, then you know how annoying it can be to deal with axios timeout.

Axios is a popular JavaScript library for making HTTP requests, widely used by developers for building web applications. It has many features and options that make it easy and convenient to use, such as interceptors, transformers, cancel tokens, and more. But one of the most important and often overlooked options is the timeout.

The timeout option allows you to specify how long axios should wait for a response from the server before giving up and throwing an error. This is useful for preventing your application from hanging or crashing when the server is slow, unavailable, or unreliable. By setting a reasonable timeout value, you can handle axios timeout gracefully and provide a better user experience.

But how do you choose the right timeout value? How do you handle the timeout error when it occurs? And how do you test and debug your axios requests with timeout with Apidog.

💡
Test and debug your axios requests with timeout using Apidog, an integrated platform for API design, debugging, development, mock, and testing for free.
button

What is Axios Timeout and Why It Matters

Before we dive into the details of how to handle axios timeout, let’s first understand what it is and why it matters.

Axios timeout is the maximum amount of time that axios will wait for a response from the server before aborting the request and throwing an error. The default timeout value in axios is 0, which means there is no timeout and axios will wait indefinitely for a response.

This might sound like a good idea, because you don’t want to miss any response from the server, right? Well, not really. There are many reasons why waiting indefinitely for a response is a bad idea, such as:

  • The server might be down, offline, or unreachable, and never send a response
  • The server might be overloaded, slow, or busy, and take too long to send a response
  • The network might be unstable, congested, or interrupted, and cause delays or failures in the communication
  • The user might lose interest, patience, or connection, and close the browser or switch to another app

In any of these cases, waiting indefinitely for a response will result in a poor user experience, a wasted resource, and a potential security risk. Imagine if your user is trying to make a payment, and the server takes forever to process it. The user might think that the payment failed, and try to make it again, resulting in a double charge. Or worse, the user might give up and leave your site, resulting in a lost sale.

That’s why setting a timeout value in axios is important. By setting a timeout value, you can tell axios to give up on the request after a certain period of time, and throw an error. This way, you can handle the error in your code, and provide a fallback or alternative option to the user, such as:

  • Showing an error message or a loading indicator
  • Asking the user to retry or refresh the page
  • Redirecting the user to another page or service
  • Logging the error or sending a notification to the developer

By handling the error, you can improve the user experience, save the resource, and prevent the security risk. You can also avoid unnecessary or duplicate requests, and optimize the performance of your application.

But how do you set the timeout value in axios? And how do you handle the error when it occurs? That’s what we will see in the next sections.

How to Set the Timeout Option in Axios

Setting the timeout option in axios is very easy and straightforward. You can specify the timeout value in milliseconds as a property of the config object that you pass to the axios request method, such as axios.get, axios.post, axios.put, etc.

For example, if you want to set the timeout value to 5 seconds (5000 milliseconds) for a GET request to a certain API endpoint, you can write something like this:

axios.get('/api/users', {timeout: 5000})
  .then(response => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

Alternatively, you can also set the timeout value globally for all axios requests, by using the axios.defaults object. For example, if you want to set the timeout value to 5 seconds for all axios requests, you can write something like this:

axios.defaults.timeout = 5000;

You can also create an axios instance with a custom timeout value, and use it for specific requests. For example, if you want to create an axios instance with a timeout value of 10 seconds, and use it for some requests, you can write something like this:

const instance = axios.create({timeout: 10000});

instance.get('/api/products')
  .then(response => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

As you can see, setting the timeout option in axios is very simple and flexible. You can customize it for different requests, depending on your needs and preferences.

Boost Your Productivity: How axios.create Simplifies API Integration
Discover the magic of axios.create – your secret weapon for seamless API calls. Learn how to configure custom instances, handle errors, and optimize performance. Get ready to level up your development game

But how do you choose the right timeout value for your requests? How long should you wait for a response before giving up? There is no definitive answer to this question, as it depends on many factors, such as:

  • The type and purpose of the request
  • The speed and reliability of the server and the network
  • The expectation and tolerance of the user
  • The availability and feasibility of the fallback or alternative option

In general, you should choose a timeout value that is reasonable and realistic, based on the average response time of the server and the network, and the worst-case scenario of the request. You should also consider the user’s perspective, and try to balance the trade-off between waiting for a response and providing a feedback.

For example, if you are making a request that is critical and time-sensitive, such as a payment or a booking, you might want to set a shorter timeout value, such as 3 or 5 seconds, and provide a clear and immediate feedback to the user, such as a loading indicator or a retry button. On the other hand, if you are making a request that is less critical and more flexible, such as a search or a recommendation, you might want to set a longer timeout value, such as 10 or 15 seconds, and provide a subtle and gradual feedback to the user, such as a progress bar or a placeholder.

Of course, these are just some examples and suggestions, and you should always test and adjust your timeout values according to your specific situation and requirements.

But what happens when the timeout value is reached, and the request is aborted? How do you catch and handle the timeout error in axios? That’s what we will see in the next section.

How to Catch and Handle the Timeout Error in Axios

When the timeout value is reached, and the request is aborted, axios will throw an error, which you can catch and handle in your code. There are different ways to catch and handle the error, depending on how you write your axios requests, such as using try/catch, promises, or async/await.

Using try/catch

If you are using try/catch to write your axios requests, you can catch the error in the catch block, and handle it accordingly. For example, if you are using a try/catch block to make a GET request to a certain API endpoint, with a timeout value of 5 seconds, you can write something like this:

try {
  const response = await axios.get('/api/users', {timeout: 5000});
  // handle success
} catch (error) {
  // handle error
}

But how do you know if the error is a timeout error, or some other type of error? One way to check is to use the error.code property, which will be set to ‘ECONNABORTED’ if the error is a timeout error. For example, you can write something like this:

try {
  const response = await axios.get('/api/users', {timeout: 5000});
  // handle success
} catch (error) {
  // handle error
  if (error.code === 'ECONNABORTED') {
    // handle timeout error
    console.error('Request timed out');
    // do something else, such as showing an error message or a retry button
  } else {
    // handle other types of errors
    console.error(error.message);
    // do something else, such as logging the error or sending a notification
  }
}

As you can see, using try/catch is a simple and effective way to catch and handle the timeout error in axios. However, it requires using the async/await syntax, which might not be supported by some browsers or environments. If you want to use a more compatible and traditional way to write your axios requests, you can use promises instead.

Using promises

If you are using promises to write your axios requests, you can catch the error in the catch method, and handle it accordingly. For example, if you are using a promise chain to make a GET request to a certain API endpoint, with a timeout value of 5 seconds, you can write something like this:

axios.get('/api/users', {timeout: 5000})
  .then(response => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

To check if the error is a timeout error, you can use the same error.code property as before, and compare it with ‘ECONNABORTED’. For example, you can write something like this:

axios.get('/api/users', {timeout: 5000})
  .then(response => {
    // handle success
  })
  .catch(error => {
    // handle error
    if (error.code === 'ECONNABORTED') {
      // handle timeout error
      console.error('Request timed out');
      // do something else, such as showing an error message or a retry button
    } else {
      // handle other types of errors
      console.error(error.message);
      // do something else, such as logging the error or sending a notification
    }
  });

As you can see, using promises is another easy and familiar way to catch and handle the timeout error in axios. However, it might result in a nested and verbose code, especially if you have multiple axios requests in a sequence or in parallel. If you want to use a more modern and elegant way to write your axios requests, you can use async/await instead.

Using async/await

If you are using async/await to write your axios requests, you can catch the error in a try/catch block, and handle it accordingly. This is the same method that we saw earlier, but I will repeat it here for completeness. For example, if you are using an async function to make a GET request to a certain API endpoint, with a timeout value of 5 seconds, you can write something like this:

async function getUsers() {
  try {
    const response = await axios.get('/api/users', {timeout: 5000});
    // handle success
  } catch (error) {
    // handle error
    if (error.code === 'ECONNABORTED') {
      // handle timeout error
      console.error('Request timed out');
      // do something else, such as showing an error message or a retry button
    } else {
      // handle other types of errors
      console.error(error.message);
      // do something else, such as logging the error or sending a notification
    }
  }
}

As you can see, using async/await is a clean and concise way to catch and handle the timeout error in axios. However, it requires using the async/await syntax, which might not be supported by some browsers or environments. If you want to use a more compatible and traditional way to write your axios requests, you can use promises instead.

These are the three main ways to catch and handle the timeout error in axios, using try/catch, promises, or async/await. You can choose the one that suits your preference and situation best, and use it consistently throughout your code.

But how do you test and debug your axios requests with timeout?

How to Test and Debug Your Axios Requests with Timeout Using Apidog

Apidog is a powerful and easy-to-use platform that helps you design, debug, develop, mock, and test your APIs. It has many features and tools that make it a one-stop solution for all your API needs.

button
  • Open Apidog and click on the “New Request” button to create a new request
  • You will see a request editor, where you can enter the details of your request, such as method, URL, headers, body, etc.
  • Click on the “Send” button to send the request
  • You will see a response panel, where you can see the details of the response, such as status, headers, body, time, etc.

With Apidog, you can easily test and debug your axios requests with timeout.

Conclusion

In this blog post, we have learned how to handle axios timeout like a pro, using the best practices and tools available. We have seen how to:

  • Set the timeout option in axios and customize it for different requests
  • Catch and handle the timeout error in axios using try/catch, promises, or async/await
  • Test and debug your axios requests with timeout using Apidog, an integrated platform for API design, debugging, development, mock, and testing

By following these steps, you can improve the user experience, performance, and security of your web applications, and avoid the frustration and hassle of waiting indefinitely for a response from the server.

button

Join Apidog's Newsletter

Subscribe to stay updated and receive the latest viewpoints anytime.