{"id":10503,"date":"2025-10-21T17:32:42","date_gmt":"2025-10-21T17:32:41","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10503"},"modified":"2025-10-21T17:32:42","modified_gmt":"2025-10-21T17:32:41","slug":"axios-in-practice-interceptors-cancellation-tokens-and-retries","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/axios-in-practice-interceptors-cancellation-tokens-and-retries\/","title":{"rendered":"Axios in Practice: Interceptors, Cancellation Tokens, and Retries"},"content":{"rendered":"<h1>Mastering Axios: Interceptors, Cancellation Tokens, and Retries<\/h1>\n<p>In the world of modern web applications, handling asynchronous operations such as HTTP requests is an essential skill for developers. Axios, a promise-based HTTP client for JavaScript, has gained immense popularity due to its simplicity, versatility, and ease of use with both browsers and Node.js. This article will explore some of advanced features of Axios, including interceptors, cancellation tokens, and retry mechanisms, enabling you to handle HTTP requests more efficiently.<\/p>\n<h2>Table of Contents<\/h2>\n<ul>\n<li><a href=\"#introduction\">Introduction to Axios<\/a><\/li>\n<li><a href=\"#interceptors\">Understanding Interceptors<\/a><\/li>\n<li><a href=\"#cancellation-tokens\">Using Cancellation Tokens<\/a><\/li>\n<li><a href=\"#retries\">Implementing Retries<\/a><\/li>\n<li><a href=\"#best-practices\">Best Practices for Axios<\/a><\/li>\n<li><a href=\"#conclusion\">Conclusion<\/a><\/li>\n<\/ul>\n<h2 id=\"introduction\">Introduction to Axios<\/h2>\n<p>Axios simplifies the process of making HTTP requests, handling responses, and managing errors. With its async features and support for promises, developers can write cleaner, more maintainable code. Here\u2019s how you can set up Axios in your project:<\/p>\n<pre><code>npm install axios<\/code><\/pre>\n<p>You can then import Axios in your JavaScript file:<\/p>\n<pre><code>import axios from 'axios';<\/code><\/pre>\n<p>Now you\u2019re ready to start making requests!<\/p>\n<h2 id=\"interceptors\">Understanding Interceptors<\/h2>\n<p>Interceptors are a powerful feature in Axios that allow you to globally handle requests or responses before they are sent or received. This is invaluable for tasks such as adding authentication tokens, logging, error handling, and more.<\/p>\n<h3>Request Interceptors<\/h3>\n<p>Request interceptors can be used to modify a request configuration before it is sent. For example, if you want to attach an authorization token to every request, you can do so as follows:<\/p>\n<pre><code>axios.interceptors.request.use(config =&gt; {\n    const token = 'your-auth-token'; \/\/ Replace with your token logic\n    if(token) {\n        config.headers['Authorization'] = `Bearer ${token}`;\n    }\n    return config;\n}, error =&gt; {\n    return Promise.reject(error);\n});<\/code><\/pre>\n<p>In this code, before sending any request, Axios will check for an authorization token and attach it to the request headers.<\/p>\n<h3>Response Interceptors<\/h3>\n<p>Response interceptors can be used to process responses or handle errors globally. Here\u2019s an example of how to simplify error handling:<\/p>\n<pre><code>axios.interceptors.response.use(response =&gt; {\n    return response;\n}, error =&gt; {\n    \/\/ Handle error globally\n    console.error('API error occurred:', error.response.status);\n    return Promise.reject(error);\n});<\/code><\/pre>\n<p>In this snippet, if any API call fails, it logs the error status, which can be essential for debugging.<\/p>\n<h2 id=\"cancellation-tokens\">Using Cancellation Tokens<\/h2>\n<p>In complex applications where multiple requests may be made simultaneously, managing the cancellation of previous requests before making a new one can enhance performance and user experience. Axios supports cancellation tokens, which allows you to cancel requests easily.<\/p>\n<h3>Creating a Cancellation Token<\/h3>\n<p>You can create a cancellation token using the built-in <code>CancelToken<\/code> source:<\/p>\n<pre><code>const CancelToken = axios.CancelToken;\nconst source = CancelToken.source();\n\n\/\/ Making a GET request\naxios.get('\/some\/endpoint', {\n    cancelToken: source.token\n}).then(response =&gt; {\n    console.log(response.data);\n}).catch(thrown =&gt; {\n    if (axios.isCancel(thrown)) {\n        console.warn('Request canceled', thrown.message);\n    } else {\n        \/\/ Handle error\n        console.error('An error occurred:', thrown);\n    }\n});<\/code><\/pre>\n<h3>Canceling a Request<\/h3>\n<p>To cancel the request, call the <code>cancel<\/code> method of the source:<\/p>\n<pre><code>source.cancel('Operation canceled by the user.');<\/code><\/pre>\n<p>This approach ensures that unnecessary requests do not consume bandwidth and resources, leading to a more efficient application.<\/p>\n<h2 id=\"retries\">Implementing Retries<\/h2>\n<p>Sometimes, network requests may fail due to temporary issues. Implementing retries can be crucial to improving the resilience of your application. You can achieve this in Axios with some custom logic.<\/p>\n<h3>Basic Retry Logic<\/h3>\n<p>Here\u2019s a simple example of how you could implement a retry mechanism:<\/p>\n<pre><code>\nconst axiosRetry = (axiosInstance, retries = 3) =&gt; {\n    axiosInstance.interceptors.response.use(null, async (error) =&gt; {\n        const { config } = error;\n        if (!config || !retries) return Promise.reject(error);\n\n        config.__retryCount = config.__retryCount || 0;\n\n        if (config.__retryCount &gt;= retries) {\n            return Promise.reject(error);\n        }\n\n        config.__retryCount += 1;\n        \n        return await new Promise((resolve) =&gt; {\n            setTimeout(() =&gt; {\n                resolve(axiosInstance(config));\n            }, 1000); \/\/ Retry after a second\n        });\n    });\n};\n\naxiosRetry(axios);\n<\/code><\/pre>\n<h2 id=\"best-practices\">Best Practices for Axios<\/h2>\n<p>When working with Axios, consider the following best practices to ensure cleaner and maintainable code:<\/p>\n<ul>\n<li><strong>Use Interceptors Wisely<\/strong>: Utilize interceptors for things like authentication and logging, but avoid complex logic that makes debugging challenging.<\/li>\n<li><strong>Centralize Your Configuration<\/strong>: Create a centralized Axios instance with default settings tailored to your application\u2019s needs to avoid repetition.<\/li>\n<li><strong>Handle Errors Gracefully<\/strong>: Implement global error handling in your application to provide users with appropriate feedback.<\/li>\n<li><strong>Clean Up with Cancellation<\/strong>: Use cancellation tokens for requests that can be canceled to avoid leaks and to optimize performance.<\/li>\n<li><strong>Implement Retry Logic<\/strong>: Use retry mechanisms for recoverable errors to enhance user experience and reliability of API interactions.<\/li>\n<\/ul>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Understanding and utilizing Axios features like interceptors, cancellation tokens, and retry logic can greatly enhance your ability to manage HTTP requests in your applications. With these tools at your disposal, you can build more resilient, user-friendly web applications. As you continue to implement these features, always keep best practices in mind to ensure your codebase remains maintainable and efficient.<\/p>\n<p>Happy Coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Mastering Axios: Interceptors, Cancellation Tokens, and Retries In the world of modern web applications, handling asynchronous operations such as HTTP requests is an essential skill for developers. Axios, a promise-based HTTP client for JavaScript, has gained immense popularity due to its simplicity, versatility, and ease of use with both browsers and Node.js. This article will<\/p>\n","protected":false},"author":136,"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":["post-10503","post","type-post","status-publish","format-standard","category-web-development","tag-axios","tag-error-handling","tag-http-client"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10503","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\/136"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10503"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10503\/revisions"}],"predecessor-version":[{"id":10504,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10503\/revisions\/10504"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}