How To Use Axios Interceptors To Refresh Your API Token?

This blog discusses how to refresh an access token using Axios Interceptors.

Table of Contents

    Axios Interceptors To Refresh Your API Token:

    Recently, we have been working on making our software more secure; on the way, we had to implement a logic where our authorization token will expire in some time, so we need to generate a new access token with the help of a refresh token. We found a blog from “the dutch lab,” which discusses how to do the job. But this blog seems to assume that our front end will fire one request at a time, which is not practical for real-world applications.

    Instead, what is expected in real-world applications is that the front end will be firing multiple API calls at a time, and they can also be sequential, and if the sequential API calls are not called again in sequence, then your UI logic will definitely break. And at the same time, if the token expires, it should not generate authorization tokens multiple times. Hence we have done a workaround that can save you three days.

    Briefly, we can handle it in two ways:-

    1. Check if the API responds with “Unauthorized access”; if yes, generate a new token, and fire the same request again. (discussed below)
    2. While making the request itself, first check if the access token is expired or not; if expired, then generate a new token and then make the request (more effective). Working is more or less the same; while handling the request, we will check all and then, at last, make the request.

    The Solution: -

    We are using cookies because one cookie will be the same across multiple API calls, just like static variable acts in class. Hence this will implement a singleton approach.

    Conclusion

    To conclude, in an Axios response interceptor, we pass the original response to a response handler function that does the logic and returns with a new response. Hence, we return a new response.

    In the response handler function, we check if the API response is unauthorized access, then we will check if the new access token is already requested then we will wait until it gets a new access token; once we get it, we will fire the same request which failed initially and gets the new response and return it.

    If the new access token is not already requested, then we will generate an access token, and once we get a new access token, we will re-request the failed API and get a new response and return it. On the other hand, if we implement it on the Axios request handler, then first we check if the authorization token is already expired or not, if expired we will request a new token until other requests will wait once the new token comes, all requests get fired, and we get our response typically.

    Don't forget to share this post!

    Level Up Your Onboarding & Implementation Process!

    Get Started