{"id":11110,"date":"2025-11-13T19:25:47","date_gmt":"2025-11-13T19:25:47","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11110"},"modified":"2025-11-13T19:25:47","modified_gmt":"2025-11-13T19:25:47","slug":"axios-in-production-retries-cancellation-and-timeouts-2","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/axios-in-production-retries-cancellation-and-timeouts-2\/","title":{"rendered":"Axios in Production: Retries, Cancellation, and Timeouts"},"content":{"rendered":"<h1>Axios in Production: Implementing Retries, Cancellation, and Timeouts<\/h1>\n<p>As modern web applications become increasingly reliant on APIs, managing HTTP requests effectively is crucial. Axios, a promise-based HTTP client for JavaScript, provides a simple and intuitive interface for making those API calls. However, in production environments, handling requests effectively goes beyond just sending and receiving data; it involves managing retries, cancellations, and timeouts. In this article, we will explore how to implement these features in your Axios-based applications, ensuring resilient and user-friendly interactions with APIs.<\/p>\n<h2>Table of Contents<\/h2>\n<ul>\n<li><a href=\"#why-axios\">Why Use Axios?<\/a><\/li>\n<li><a href=\"#retries\">Implementing Retries<\/a><\/li>\n<li><a href=\"#cancellation\">Request Cancellation<\/a><\/li>\n<li><a href=\"#timeouts\">Handling Timeouts<\/a><\/li>\n<li><a href=\"#best-practices\">Best Practices for Axios in Production<\/a><\/li>\n<li><a href=\"#conclusion\">Conclusion<\/a><\/li>\n<\/ul>\n<h2 id=\"why-axios\">Why Use Axios?<\/h2>\n<p>Axios has become a go-to choice for JavaScript developers due to its features:<\/p>\n<ul>\n<li><strong>Promise-based API:<\/strong> Makes handling asynchronous operations easier.<\/li>\n<li><strong>Interceptors:<\/strong> Allow for global request and response manipulation.<\/li>\n<li><strong>Automatic JSON transformation:<\/strong> Automatically converts requests and responses to JSON.<\/li>\n<li><strong>Browser compatibility:<\/strong> Works seamlessly with modern JavaScript environments.<\/li>\n<\/ul>\n<p>These features, among others, make Axios a robust choice for API interactions in your applications.<\/p>\n<h2 id=\"retries\">Implementing Retries<\/h2>\n<p>Network failures can happen for a variety of reasons, such as temporary server issues, internet connectivity loss, or timeouts. Implementing retries can help mitigate these failures.<\/p>\n<p>To implement retries, you can create a custom Axios instance and add some logic. Below is an example of how to achieve this using an Axios instance interceptor:<\/p>\n<pre><code>\nconst axios = require('axios');\n\nconst axiosInstance = axios.create({\n  baseURL: 'https:\/\/api.example.com',\n  timeout: 10000,\n});\n\n\/\/ Function to create a retry logic\nconst retryRequest = async (requestFunc, retries) =&gt; {\n  for (let i = 0; i &lt; retries; i++) {\n    try {\n      return await requestFunc();\n    } catch (error) {\n      if (i === retries - 1) {\n        throw error; \/\/ fail on final attempt\n      }\n      console.log(`Retrying request... Attempt ${i + 1}`);\n    }\n  }\n};\n\n\/\/ Example usage of retry logic\naxiosInstance.get('\/data')\n  .then(response =&gt; {\n    console.log(response.data);\n  })\n  .catch(error =&gt; {\n    console.error('Request failed:', error);\n  });\n<\/code><\/pre>\n<p>In this snippet, we create an Axios instance and define a <code>retryRequest<\/code> function which attempts a request multiple times before giving up. The <code>requestFunc<\/code> parameter is a function that performs the actual Axios call.<\/p>\n<h2 id=\"cancellation\">Request Cancellation<\/h2>\n<p>Request cancellation is important in scenarios where user interactions occur rapidly, such as typing in a search box. You may want to cancel previous API requests when the user makes a new search request to improve performance and user experience.<\/p>\n<p>Axios provides a <code>CancelToken<\/code> that can be used to abort requests. Here&#8217;s how to use it:<\/p>\n<pre><code>\nconst axios = require('axios');\nconst CancelToken = axios.CancelToken;\nlet cancel;\n\nconst fetchData = (query) =&gt; {\n  if (cancel) {\n    cancel(); \/\/ Cancel the previous request\n  }\n\n  axios.get('\/search', {\n    params: { q: query },\n    cancelToken: new CancelToken((c) =&gt; {\n      cancel = c;\n    })\n  })\n  .then(response =&gt; {\n    console.log(response.data);\n  })\n  .catch(error =&gt; {\n    if (axios.isCancel(error)) {\n      console.log('Request canceled', error.message);\n    } else {\n      console.error('Error fetching data:', error);\n    }\n  });\n};\n\n\/\/ Usage\nfetchData('initial query');\nsetTimeout(() =&gt; fetchData('new query'), 200); \/\/ Simulate user typing\n<\/code><\/pre>\n<p>In the above example, we set up a function <code>fetchData<\/code> that cancels any ongoing request when a new request is made. The <code>CancelToken<\/code> helps to manage this cancellation gracefully.<\/p>\n<h2 id=\"timeouts\">Handling Timeouts<\/h2>\n<p>Timeouts are critical in ensuring that your application remains responsive. By setting appropriate timeout values for your Axios requests, you can avoid long waits and give users feedback when things go wrong.<\/p>\n<p>Here&#8217;s how to set a timeout in Axios requests:<\/p>\n<pre><code>\nconst axios = require('axios');\n\nconst axiosInstance = axios.create({\n  baseURL: 'https:\/\/api.example.com',\n  timeout: 5000, \/\/ Set timeout to 5 seconds\n});\n\n\/\/ Making a request\naxiosInstance.get('\/data')\n  .then(response =&gt; {\n    console.log(response.data);\n  })\n  .catch(error =&gt; {\n    if (error.code === 'ECONNABORTED') {\n      console.error('Request timeout:', error.message);\n    } else {\n      console.error('Error fetching data:', error);\n    }\n  });\n<\/code><\/pre>\n<p>In this code, the instance is configured with a timeout of 5 seconds. If the request does not complete within this time, it will be aborted, and an error will be caught and handled appropriately.<\/p>\n<h2 id=\"best-practices\">Best Practices for Axios in Production<\/h2>\n<p>To ensure optimal performance and reliability of your API calls, consider the following best practices:<\/p>\n<ul>\n<li><strong>Use Interceptors:<\/strong> Leverage Axios interceptors to apply common headers, logging, or handle errors globally.<\/li>\n<li><strong>Manage configurations centrally:<\/strong> Define a base Axios instance with a predefined configuration to maintain consistency across requests.<\/li>\n<li><strong>Implement error handling:<\/strong> Always handle errors gracefully to provide meaningful feedback to users.<\/li>\n<li><strong>Monitor API performance:<\/strong> Keep logs and monitor response times and error rates for resilience.<\/li>\n<li><strong>Test thoroughly:<\/strong> Write unit tests to ensure that your Axios logic behaves as expected under various scenarios.<\/li>\n<\/ul>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Incorporating retries, cancellation, and timeouts in your Axios setup enhances the robustness of your applications. By leveraging these features, developers can create user-friendly interfaces that improve the overall user experience. Every API interaction counts, and having a resilient HTTP client like Axios can make a significant difference. By following the practices outlined in this blog, you will be in a great position to deploy applications ready for production and capable of gracefully handling the inevitable challenges of API calls.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Axios in Production: Implementing Retries, Cancellation, and Timeouts As modern web applications become increasingly reliant on APIs, managing HTTP requests effectively is crucial. Axios, a promise-based HTTP client for JavaScript, provides a simple and intuitive interface for making those API calls. However, in production environments, handling requests effectively goes beyond just sending and receiving data;<\/p>\n","protected":false},"author":180,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[203],"tags":[913,1020,914],"class_list":{"0":"post-11110","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-web-development","7":"tag-axios","8":"tag-error-handling","9":"tag-http-client"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11110","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/180"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=11110"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11110\/revisions"}],"predecessor-version":[{"id":11112,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11110\/revisions\/11112"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11110"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11110"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11110"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}