How to Implement Refresh-Token Functionality (Front-End).

Ifeanyi Ibekie
The Startup
Published in
5 min readSep 25, 2020
Security

Security in front-end applications differ based on requirements and as an engineer, your task is to meet those requirements while keeping a remarkable experience for your users. Using the Bearer Token authentication mechanism you would notice some differences in the approach when designing some applications. Financial apps require constant authentication and re-authentication to protect access to your money, but for less serious apps like educational apps and apps for media consumption it's going to be a bad experience for your users to be reauthenticating themselves anytime they come back to your app. Before you proceed with this article there are certain things you should be aware of:

  1. This article only covers the Bearer Token method of authentication in building applications.
  2. This article assumes you have adequate knowledge of authentication using the Bearer Token method.
  3. This article assumes you have proper knowledge of Axios (Promise based HTTP client for the browser and node.js).
  4. This article assumes you are using Axios for your HTTP client as using other clients may differ.
  5. This article does not cover the back-end aspect of a refresh-token functionality. It assumes the API’s are ready for the refresh-token and is supposed to guide you on how to go about implementing the front-end aspect.

THE PROBLEM

The defacto way for building applications is to authenticate your users then when the backend invalidates their token you throw them back at a log-in page which works but it may break the flow of usage for the application. Imagine you scrolling through your Instagram and you were to leave it for say a day and the moment you revisit it, it slams you back at a log-in page. It is not rocket science to discover when such an experience becomes a bottleneck and a suitable solution to this is to implement a refresh-token functionality for your application whereas when the token has expired quickly request for a new one. In order to fully implement this solution we need to come up with answers to the following questions:

  1. How would a refresh token work?
  2. What data do we need to implement a refresh-token solution?
  3. Where/how would we store/read our refresh-token related data?
  4. How do we effectively implement the refresh token functionality with axios?
  5. How do we effectively implement the refresh token functionality with our router?

HOW WOULD A REFRESH TOKEN WORK?

This step is basically the planning stage. This is where we mind-map the entire process we would be implementing in code. Since we cannot tell for sure what page or activity a user would be at when their token expires while using our application, We need to determine the points to hook our refresh token functionality, they are:

1. HTTP Client: The HTTP client is a perfect point to hook our refresh token solution. This is because our HTTP client would be responsible for sending requests to our backend service and returning the responses. It is a no brainer to choose this point as this is the first point of detection of an expired token, as when you place a request with an expired token the backend would respond with an authentication error and it is at this point we can effectively request for a token refresh.

2. Router Instance: Most Frontend frameworks provide us with a router/routing instance to navigate users through our application. These routing instances usually support hooks based on various navigation events/stages like before a page load or on page enter and so on. The router instance would be an excellent point to hook our refresh token solution as when a user is transitioning between pages or when the application is rehydrated from a minimized browser tab, we can run a quick check on the validity of our current token and refresh it before entering the page.

WHAT DATA DO WE NEED TO IMPLEMENT A REFRESH-TOKEN SOLUTION?

Now that we have been able to understand how a refresh token should work we need to understand the data we would need to implement this.

  1. Expiry: To implement a refresh-token solution, especially for our router instance we need an expiry value, which would have the sole purpose of telling us when the token is expired. This value would be set with a post-dated timestamp of say 5mins before the back-end service would normally flag the token invalid. This is so that across refreshes and reloads we can know that our token has expired and this value will be updated whenever the token is updated.
  2. Token: This is a no brainer as in order to refresh a token we would need the old token. To that effect, we need to store our bearer token anytime an authentication is complete as when we have the current token stored the moment it expires we use it to request for a new one and as such it should also be updated with the most recent token.

WHERE/HOW WOULD WE STORE/READ OUR REFRESH-TOKEN RELATED DATA?

Completing the previous step the next question is where these refresh-token data would be stored? Spoiler Alert, Localstorage. We chose to use localstorage because this data has to survive across page refreshes and localstorage is one of the easiest Web Apis to use when persisting data across browser sessions.

Above is the helper file we would use to help with storing and reading from the localstorage with encryption built-in.

HOW DO WE IMPLEMENT THE REFRESH TOKEN FUNCTIONALITY WITH AXIOS?

Now, to get our hands dirty. With our localstorage helper methods, we need to set up the integration with axios. To integrate with axios we are going to be making use of axios interceptors (https://github.com/axios/axios#interceptors).

From the file above you can see that the flow is to check the error message from the API and if it's our expected error message for an invalid token, we refresh the token and as soon as that is complete we retry the initial request with the updated axios instance, Easy.

HOW DO WE IMPLEMENT THE REFRESH TOKEN FUNCTIONALITY WITH ROUTER?

Now to integrate with our routing library. My routing library of choice for this example is the Vue router because why not vue, lol. This should be extensible and simple enough to make meaning in any other routing library.

The flow is before any route action is completed check if it is a protected route that would need a valid token. if the token is valid? allow through, if the token is not valid? attempt to refresh token then allow through if successful. The rest are all fallbacks for errors or handles for unprotected routes.

The concept of implementing a refresh-token functionality is easy and I hope this tutorial has shown you how to go by it in your daily development should such a requirement come up. Happy Coding.

--

--