{"id":23890,"date":"2024-03-14T19:01:53","date_gmt":"2024-03-14T13:31:53","guid":{"rendered":"https:\/\/blogrevamp.cashfree.com\/?p=23890"},"modified":"2025-05-26T14:22:41","modified_gmt":"2025-05-26T08:52:41","slug":"axios-interceptors-jwt-refresh-react-native","status":"publish","type":"post","link":"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/","title":{"rendered":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_81 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #005c31;color:#005c31\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #005c31;color:#005c31\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#JWT_Refresh_Token_Flow_in_React_Native_Apps\" >JWT Refresh Token Flow in React Native Apps<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#_How_to_Set_up_Axios_for_Token_Management_in_React_Native\" >\u00a0How to Set up Axios for Token Management in React Native<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#Enhancing_JWT_Security_with_Axios_Interceptors\" >Enhancing JWT Security with Axios Interceptors<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#Request_Interceptors\" >Request Interceptors<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#Response_Interceptors\" >Response Interceptors<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#Handling_a_401_Response_in_Axios_Interceptors\" >Handling a 401 Response in Axios Interceptors<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/#Code_Example_for_JWT_Token_Refresh_in_Axios\" >Code Example for JWT Token Refresh in Axios<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\t\t<div data-elementor-type=\"wp-post\" data-elementor-id=\"23890\" class=\"elementor elementor-23890\">\n\t\t\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7c4297e6 elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"7c4297e6\" data-element_type=\"section\" data-e-type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-9821c32\" data-id=\"9821c32\" data-element_type=\"column\" data-e-type=\"column\">\n\t\t\t<div class=\"elementor-widget-wrap elementor-element-populated\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-112827dd elementor-widget elementor-widget-text-editor\" data-id=\"112827dd\" data-element_type=\"widget\" data-e-type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>Developing a secure and smooth app, especially for payments, is crucial. In creating the Cashfree Payments app with React Native, we focused on top-notch security and easy user experience. Key to our strategy is handling JSON Web Tokens (JWT) efficiently for user sessions.\u00a0<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>We used Axios, a JavaScript library, to refresh JWTs seamlessly through interceptors. This method improves security and user experience by updating tokens automatically, without user interruption.\u00a0<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>In this guide, we share insights on integrating JWT refresh in React Native apps with Axios, providing valuable tips for developers on enhancing authentication processes easily.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:heading {\"level\":1} --><\/p>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"JWT_Refresh_Token_Flow_in_React_Native_Apps\"><\/span>JWT Refresh Token Flow in React Native Apps<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:image {\"align\":\"center\",\"id\":23901,\"sizeSlug\":\"large\",\"linkDestination\":\"none\"} --><\/p>\n<figure class=\"wp-block-image aligncenter size-large\"><img fetchpriority=\"high\" decoding=\"async\" data-attachment-id=\"23901\" data-permalink=\"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/axiom_d1_v3\/\" data-orig-file=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?fit=2319%2C1337&amp;ssl=1\" data-orig-size=\"2319,1337\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"Axiom_D1_V3\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?fit=770%2C444&amp;ssl=1\" data-recalc-dims=\"1\" height=\"444\" width=\"770\" class=\"wp-image-23901\" src=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?resize=770%2C444&#038;ssl=1\" alt=\"\" srcset=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?w=2319&amp;ssl=1 2319w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?resize=300%2C173&amp;ssl=1 300w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?resize=1024%2C590&amp;ssl=1 1024w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?resize=768%2C443&amp;ssl=1 768w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_D1_V3.jpg?resize=1536%2C886&amp;ssl=1 1536w\" sizes=\"(max-width: 770px) 100vw, 770px\" \/><\/figure>\n<p><!-- \/wp:image --><\/p>\n<p><!-- wp:list {\"ordered\":true} --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol><!-- wp:list-item --><\/ol>\n<\/li>\n<\/ol>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>The client initiates the authentication process by sending a POST request with their username and password to the server&#8217;s <strong>\/api\/auth\/signin<\/strong> endpoint.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>Upon successful authentication, the server generates and returns a JSON Web Token (JWT) along with a `refreshToken`, user information, and roles.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>The client adds the JWT to the Authorisation header of every subsequent request to access protected resources.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>If the server detects an expired JWT, indicated by a TokenExpiredError, it notifies the client.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>The client requests a new JWT using the `refreshToken` by sending a POST request to <strong>\/api\/auth\/refreshtoken.<\/strong><\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>The server verifies the `refreshToken` and, upon successful validation, issues a new JWT and possibly a new `refreshToken`.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>This process ensures secure and efficient user authentication and session management in the application.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:heading --><\/p>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"_How_to_Set_up_Axios_for_Token_Management_in_React_Native\"><\/span>\u00a0How to Set up Axios for Token Management in React Native<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>Axios is initialised with <strong>axios.create(),<\/strong> providing a tailored Axios instance with specific configuration options to enhance HTTP request handling. Key configurations include:<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:list --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul><!-- wp:list-item --><\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>Setting the <em>baseURL<\/em> to <em>Config.BASE_URL<\/em>, which simplifies API interactions by automatically appending the base URL to each endpoint path. This eliminates the need for repetitive full URL specifications throughout the codebase.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>Defining a timeout limit of 60,000 milliseconds to ensure application responsiveness. This timeout acts as a safeguard against prolonged server response times, aborting requests that exceed this limit. This enhances user experience by preventing the application from becoming unresponsive during server delays.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>Creating a dedicated Axios instance like this offers several advantages:<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:list --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul><!-- wp:list-item --><\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong>Consistency:<\/strong> Every request made using this instance will automatically inherit these configurations, ensuring consistency across your application.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong>Maintainability:<\/strong> Centralising the Axios configuration makes the codebase easier to maintain. If you need to change the base URL or adjust the timeout, you only need to do it in one place.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong>Flexibility:<\/strong> If you need to request a different API or with different settings, you can easily create another instance with its configurations.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:heading --><\/p>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Enhancing_JWT_Security_with_Axios_Interceptors\"><\/span>Enhancing JWT Security with Axios Interceptors<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>Interceptors are like special helpers that work with HTTP requests and responses. They step in either right before we send a request to a server, or just after we receive a response, but before the rest of our app gets to work with that request\/response. This allows us to check our HTTP messages in specific ways, making it easier to manage things like adding security tokens to requests or consistently handling errors. This includes adjustments to configurations, headers, and payload data, thereby providing a versatile toolset for enforcing consistency, security, and data integrity across all network interactions facilitated by Axios.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>There are two types of interceptors: request interceptors and response interceptors<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:heading {\"level\":3} --><\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Request_Interceptors\"><\/span>Request Interceptors<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>The request interceptor is invoked immediately before the dispatch of a request, offering a last-minute opportunity to refine or augment the outgoing request. Common use cases include appending authentication credentials, serialising request payloads, or dynamically adjusting headers based on contextual parameters.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:list --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul><!-- wp:list-item --><\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>Before any request is made, the interceptor function retrieves the access token using <em>storage.getAccessToken()<\/em>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:list --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul><!-- wp:list-item --><\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>If the token exists, it is added to the Authorization field in the headers of the outgoing request. This standard practice ensures that each request is authenticated automatically, without the need to manually attach the token for every HTTP call. By returning <strong><em>Promise.reject(error)<\/em>,<\/strong> the error can be caught and handled in the context where the HTTP request was made<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:code --><\/p>\n<pre class=\"wp-block-code\"><code>axios.interceptors.request.use(\n (config) =&gt; {\n  \/\/ Get token and add it to header \"Authorization\" from secure storgage\n   const token = storage.getAccessToken()\n   if (token) {\n     config.headers.Authorization = token;\n   }\n   return config;\n },\n (error) =&gt; Promise.reject(error)\n);<\/code><\/pre>\n<p><!-- \/wp:code --><\/p>\n<p><!-- wp:heading {\"level\":3} --><\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Response_Interceptors\"><\/span>Response Interceptors<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>Activated upon the receipt of a response, these interceptors allow for preemptive processing of the returned data. Whether it\u2019s for global error handling, data transformation, or extracting and forwarding pertinent information, response interceptors streamline post-response processing, enhancing the robustness and resilience of the application\u2019s data-handling capabilities<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:list --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul><!-- wp:list-item --><\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>For successful responses (status codes within the 2xx range), the interceptor simply passes the response through<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- wp:list-item --><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>For responses with error status codes (outside the 2xx range), the interceptor captures these errors. This is particularly useful for centralised error handling, like logging errors or redirecting the user to an error page. By returning <em><strong>Promise.reject(error<\/strong>)<\/em>, the error can be further caught and handled in the specific context where the HTTP request was made.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!-- \/wp:list-item --><\/p>\n<p><!-- \/wp:list --><\/p>\n<p><!-- wp:code --><\/p>\n<pre class=\"wp-block-code\"><code>axios.interceptors.response.use(\n  (response) =&gt; { \n    \/\/ Any status code from range of 2xx\n    \/\/ Do something with response data\n    return response;\n  },\n  (error) =&gt; { \n    \/\/ Any status codes outside range of 2xx\n    \/\/ Do something with response error\n    return Promise.reject(error);\n  });<\/code><\/pre>\n<p><!-- \/wp:code --><\/p>\n<p><!-- wp:heading --><\/p>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Handling_a_401_Response_in_Axios_Interceptors\"><\/span><strong>Handling a 401 Response in Axios Interceptors<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>To effectively manage a 401 response, our approach involves a six-step method that begins by intercepting all server responses to identify the 401 status code<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>1. <strong>Intercepting Responses<\/strong>: Axios interceptors allow you to run your code or handle errors before the response is returned to the code that made the request. You can define a response interceptor that checks the HTTP status code of every response from the server.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>2. <strong>Detecting 401 Status Code<\/strong>: When the interceptor detects a response with a 401 status code, it recognises this as an authentication error, typically due to an expired or invalid token.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>3. <strong>Initiating Token Refresh<\/strong>: Upon detecting a 401 response, instead of immediately returning an error to the requester, the interceptor can initiate a process to refresh the token. This is done by calling a function or API endpoint dedicated to refreshing tokens. This mechanism usually involves sending a refresh token (a longer-lived token securely stored on the client) to the server to obtain a new access token<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>4. <strong>Queueing Incoming Requests<\/strong>: While the token is being refreshed, any new requests initiated by the client are queued or paused. This is because they would also fail with a 401 status if the expired or invalid token is still being used<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>5. <strong>Resuming Requests with New Token<\/strong>: Once a new access token is obtained, it is used to update the Authorization header of the original request and any queued requests. These requests can then be retried automatically without requiring the user to manually re-authenticate.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p>6. <strong>Handling Refresh Token Failure<\/strong>: If the refresh token process fails (for example, the refresh token has expired or is no longer valid), the user must be sent to a login page or asked to re-authenticate themselves manually. As a result, the user experience stays smooth and safe.<\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:heading {\"level\":3} --><\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Code_Example_for_JWT_Token_Refresh_in_Axios\"><\/span><strong>Code Example for JWT Token Refresh in Axios<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><!-- \/wp:heading --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p><strong>request.ts<\/strong><\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:code --><\/p>\n<pre class=\"wp-block-code\"><code>\nimport axios from \"axios\";\nimport tokenService from \".\/tokenService\";\nimport { authApi } from \".\/authApi\";\nimport { navigationRef } from '.\/helper';\n\nexport const BASE_URL = 'http:\/\/your-api-url.com';\n\nlet isRefreshing = false;\nlet failedQueue = [];\n\nconst request = axios.create({\n    baseURL: BASE_URL,\n    timeout: 60000\n});\n\n\/\/ Add the auth token to every request\nrequest.interceptors.request.use(\n    config =&gt; {\n        const token = tokenService.getAccessToken();\n        if (token) {\n            config.headers['Authorization'] = `Bearer ${token}`;\n        }\n        return config;\n    },\n    error =&gt; Promise.reject(error)\n);\n\nfunction subscribeTokenRefresh(cb) {\n    failedQueue.push(cb);\n}\n\nfunction onRefreshed(token) {\n    failedQueue.forEach(cb =&gt; cb(token));\n    failedQueue = [];\n}\n\nrequest.interceptors.response.use(\n    response =&gt; response,\n    err =&gt; {\n        const { config, response } = err;\n        const originalRequest = config;\n        if (response &amp;&amp; response.status === 401 &amp;&amp; !originalRequest._retry) {\n            if (!isRefreshing) {\n                isRefreshing = true;\n                return authApi.refreshToken()\n                    .then(({ access_token, refresh_token }) =&gt; {\n                     tokenService.setAccessToken(access_token);\n                      tokenService.setRefreshToken(refresh_token);\n         \t\t\t\t\t\t\trequest.defaults.headers.common['Authorization'] = `Bearer${access_token}`;        \n                        isRefreshing = false;\n                        onRefreshed(access_token);\nreturn Promise.all(failedQueue.map(cb =&gt;   cb(access_token))).then(() =&gt; {\n                            return axios(originalRequest);\n                        });\n                    })\n                    .catch(error =&gt; {\n                        isRefreshing = false;\n                        tokenService.clearTokens();\n                        navigationRef.navigate('Login');\n                        return Promise.reject(error);\n                    })\n                    .finally(() =&gt; failedQueue = []);\n            }\n\n            originalRequest._retry = true;\n            return new Promise((resolve, reject) =&gt; {\n                subscribeTokenRefresh(token =&gt; {\n                    originalRequest.headers['Authorization'] = `Bearer ${token}`;\n                    resolve(axios(originalRequest));\n                });\n            });\n        }\n\n        return Promise.reject(err);\n    }\n);\n\nexport default request;<\/code><\/pre>\n<p><!-- \/wp:code --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p><strong>helper.ts<\/strong><\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:code --><\/p>\n<pre class=\"wp-block-code\"><code>\/**\n * Provides a service for managing authentication tokens using AsyncStorage in a React Native application.\n * Includes methods to get, set, and clear both access and refresh tokens, facilitating secure and efficient\n * authentication token management throughout the app.\n *\/\nimport AsyncStorage from '@react-native-async-storage\/async-storage';\nconst tokenService = {\n    getAccessToken: () =&gt; {\n        return AsyncStorage.getItem('accessToken');\n    },\n    setAccessToken: (token) =&gt; {\n        AsyncStorage.setItem('accessToken', token);\n    },\n    getRefreshToken: () =&gt; {\n        return AsyncStorage.getItem('refreshToken');\n    },\n    setRefreshToken: (token) =&gt; {\n        AsyncStorage.setItem('refreshToken', token);\n    },\n    clearTokens: () =&gt; {\n        AsyncStorage.removeItem('accessToken');\n        AsyncStorage.removeItem('refreshToken');\n    }\n}\nexport default tokenService;\n<\/code><\/pre>\n<p><!-- \/wp:code --><\/p>\n<p><!-- wp:paragraph --><\/p>\n<p><strong>authApi.ts<\/strong><\/p>\n<p><!-- \/wp:paragraph --><\/p>\n<p><!-- wp:code --><\/p>\n<pre class=\"wp-block-code\"><code>\/**\n * Defines API calls related to refresh token \n * The refreshToken method sends a request to the server with the    current refresh token to obtain a new access token\n *\/\n\nimport axios from 'axios';\nimport { BASE_URL } from '.\/request';\n\nconst authApi = {\n    refreshToken: async () =&gt; {\n        const refreshToken = tokenService.getRefreshToken();\n        try {\nconst response = await axios.post(`${BASE_URL}\/refresh-token`,{refreshToken });                      \n           return response.data;\n        } catch (error) {\n            console.error('Error refreshing token:', error);\n            throw error;\n        }\n    }\n};<\/code><\/pre>\n<p><!-- \/wp:code --><\/p>\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<div class=\"elementor-element elementor-element-c746e68 elementor-widget elementor-widget-image\" data-id=\"c746e68\" data-element_type=\"widget\" data-e-type=\"widget\" data-widget_type=\"image.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<a href=\"https:\/\/partner.cashfree.com\/partner-ui\/authentication\/signup?source-action=BlogAFbanner&#038;action=Sign%20Up&#038;button-id=StartNow_BlogCTA\">\n\t\t\t\t\t\t\t<img decoding=\"async\" width=\"770\" height=\"288\" src=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?fit=770%2C288&amp;ssl=1\" class=\"attachment-large size-large wp-image-29656\" alt=\"\" srcset=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?w=1200&amp;ssl=1 1200w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?resize=300%2C112&amp;ssl=1 300w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?resize=1024%2C383&amp;ssl=1 1024w, https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?resize=768%2C287&amp;ssl=1 768w\" sizes=\"(max-width: 770px) 100vw, 770px\" data-attachment-id=\"29656\" data-permalink=\"https:\/\/blogrevamp.cashfree.com\/e-mandate\/blog-cta-banner\/\" data-orig-file=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?fit=1200%2C449&amp;ssl=1\" data-orig-size=\"1200,449\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"AF Blog CTA &amp;#8211; Common\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2023\/12\/Blog-CTA-banner.jpg?fit=770%2C288&amp;ssl=1\" \/>\t\t\t\t\t\t\t\t<\/a>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":"<p>Learn to implement Axios interceptors for efficient JWT refresh in React Native apps, ensuring secure and seamless user authentication for a better app experience.<\/p>\n","protected":false},"author":103,"featured_media":23905,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"_themeisle_gutenberg_block_has_review":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_wpcom_ai_launchpad_first_post":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[1497],"tags":[],"class_list":["post-23890","post","type-post","status-publish","format-standard","has-post-thumbnail","category-engineering"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs Cashfree Payments Blog<\/title>\n<meta name=\"description\" content=\"Learn how to implement JWT token refresh in React Native using Axios interceptors. Enhance API security and user experience with seamless token management and automated JWT handling.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs Cashfree Payments Blog\" \/>\n<meta property=\"og:description\" content=\"Learn how to implement JWT token refresh in React Native using Axios interceptors. Enhance API security and user experience with seamless token management and automated JWT handling.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/\" \/>\n<meta property=\"og:site_name\" content=\"Cashfree Payments Blog\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-14T13:31:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-05-26T08:52:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1\" \/>\n\t<meta property=\"og:image:width\" content=\"1205\" \/>\n\t<meta property=\"og:image:height\" content=\"821\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Shimil Jas\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Shimil Jas\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs Cashfree Payments Blog","description":"Learn how to implement JWT token refresh in React Native using Axios interceptors. Enhance API security and user experience with seamless token management and automated JWT handling.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/","og_locale":"en_US","og_type":"article","og_title":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs Cashfree Payments Blog","og_description":"Learn how to implement JWT token refresh in React Native using Axios interceptors. Enhance API security and user experience with seamless token management and automated JWT handling.","og_url":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/","og_site_name":"Cashfree Payments Blog","article_published_time":"2024-03-14T13:31:53+00:00","article_modified_time":"2025-05-26T08:52:41+00:00","og_image":[{"width":1205,"height":821,"url":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","type":"image\/jpeg"}],"author":"Shimil Jas","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Shimil Jas","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#article","isPartOf":{"@id":"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/"},"author":{"name":"Shimil Jas","@id":"https:\/\/blogrevamp.cashfree.com\/#\/schema\/person\/58ad53a65efb89f4901bb914817f3ca0"},"headline":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs","datePublished":"2024-03-14T13:31:53+00:00","dateModified":"2025-05-26T08:52:41+00:00","mainEntityOfPage":{"@id":"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/"},"wordCount":1100,"commentCount":0,"image":{"@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","articleSection":["Engineering"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/blogrevamp.cashfree.com\/axios-interceptors-jwt-refresh-react-native\/","url":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/","name":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs Cashfree Payments Blog","isPartOf":{"@id":"https:\/\/blogrevamp.cashfree.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#primaryimage"},"image":{"@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","datePublished":"2024-03-14T13:31:53+00:00","dateModified":"2025-05-26T08:52:41+00:00","author":{"@id":"https:\/\/blogrevamp.cashfree.com\/#\/schema\/person\/58ad53a65efb89f4901bb914817f3ca0"},"description":"Learn how to implement JWT token refresh in React Native using Axios interceptors. Enhance API security and user experience with seamless token management and automated JWT handling.","breadcrumb":{"@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#primaryimage","url":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","contentUrl":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","width":1205,"height":821,"caption":"Axiom"},{"@type":"BreadcrumbList","@id":"https:\/\/www.cashfree.com\/blog\/axios-interceptors-jwt-refresh-react-native\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blogrevamp.cashfree.com\/"},{"@type":"ListItem","position":2,"name":"Engineering","item":"https:\/\/blogrevamp.cashfree.com\/category\/engineering\/"},{"@type":"ListItem","position":3,"name":"A Guide to Axios Interceptors: Secure and Seamless JWT Refresh for Your APIs"}]},{"@type":"WebSite","@id":"https:\/\/blogrevamp.cashfree.com\/#website","url":"https:\/\/blogrevamp.cashfree.com\/","name":"Cashfree Payments Blog","description":"Cashfree Payments- Payment Gateway for India","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blogrevamp.cashfree.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blogrevamp.cashfree.com\/#\/schema\/person\/58ad53a65efb89f4901bb914817f3ca0","name":"Shimil Jas","url":"https:\/\/blogrevamp.cashfree.com\/author\/shimil-jas\/"}]}},"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p9MjXo-6dk","jetpack_likes_enabled":false,"jetpack_featured_media_url":"https:\/\/i0.wp.com\/blogrevamp.cashfree.com\/wp-content\/uploads\/2024\/03\/Axiom_Tn_v2.jpg?fit=1205%2C821&ssl=1","_links":{"self":[{"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/posts\/23890","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/users\/103"}],"replies":[{"embeddable":true,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/comments?post=23890"}],"version-history":[{"count":21,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/posts\/23890\/revisions"}],"predecessor-version":[{"id":29731,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/posts\/23890\/revisions\/29731"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/media\/23905"}],"wp:attachment":[{"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/media?parent=23890"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/categories?post=23890"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogrevamp.cashfree.com\/wp-json\/wp\/v2\/tags?post=23890"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}