DEV Community

Afroz Hussain
Afroz Hussain

Posted on

Token Rotation in Front-end Applications

In this post, I want to delve into the methods for managing tokens in front-end applications. I will discuss two approaches and explore the pros and cons of each.

Understanding Token Rotation

Before we dive into the solutions, let’s grasp how token rotation operates. Token rotation entails the periodic replacement of session tokens allocated to users upon logging into an application. These session tokens expire within x amount of minutes and need refreshing using the refresh token.
To understand token refresh in detail check this

There are two ways to refresh the tokens:

  • Proactively
  • Reactively

Now, let's examine each method in detail.

Proactive Token Refresh

Proactive token refresh is akin to refreshing tokens preemptively, ensuring uninterrupted user sessions and a seamless user experience. Here's how it works:

  • Initial Token Refresh: Upon loading the application, tokens are refreshed immediately to preempt expiration-related issues.

    const LoadAppdata = ()=>{
            // refresh the token
            await refreshToken();
    
            // continue loading other data
    }
    
    • Additionally, We can also add a check to refresh the token only if the token is about to expire
  • Periodic Refresh: Tokens are refreshed periodically, ideally before their expiration. For instance, if a token expires in 5 minutes, a refresh timer can be set to trigger every 4 minutes, ensuring seamless continuity of user sessions.

    const setPerodicRefresh = ()=> {
     setInterval(() => {
            // we are refreshing token every 4 min.
            refreshToken()
        }, 1000 * 60 * 4);
     };
    
     const AppLoad = ()=> {
         // other api calls
         setPerodicRefresh()
        }
    
    

Pros:

  • Enhanced User Experience: Proactive refreshes minimize disruptions, ensuring users can seamlessly interact with the application without encountering login prompts or failed requests.
  • Improved Security: By preemptively refreshing tokens, the risk of unauthorized access due to expired tokens is significantly mitigated.

Cons:

  • Multi-tab Interference: In scenarios where multiple application tabs are open simultaneously, concurrent token refresh attempts might collide, potentially leading to refresh failures.
  • Browser Inactivity: When the browser becomes inactive, timers used for token refresh may be paused or halted by the browser, potentially affecting the token rotation process.

Reactive Token Refresh

Unlike proactive refreshes, reactive token refreshes occur in response to 401’s, such as encountering an expired token during an API call. below is the setup to refresh tokens on 401’s using Axios interceptors

const errorInterceptor = async (error: any) => {
    if (!error.response) {
        return Promise.reject(error);
    }
    const originalConfig = error.config;

    // all the other error responses
    switch (error.response.status) {s
        case 400:
            console.error(error.response.status, error.message);
            break;
        case 401:
            {
                try {
                    let token = localStorage.getItem("token");
                        // if the token is not valid or is expired, refresh the token
                        const isValidToken = await fetchNewToken()
                        if (isValidToken) {
                            // if valid token is returned, retry the original request
                            let token = localStorage.getItem("token")
                            originalConfig.headers.Authorization = token;
                            // retry original request
                            try {
                                return (await axios.request(originalConfig)).data
                            } catch (innerError) {
                                // if original req failed with 401 again - it means server returned not valid token for refresh request
                                console.error(innerError)
                            }

                        } else {
                            // if token is not valid, logout user
                            console.error("Invalid token")
                            logoutUser("Session expired, please login again")
                        }

                }
                catch (err) {
                    console.error("Something went wrong", err)
                }
                console.error(error.response.status, error.message);

            }
            break;
        default:
            console.error(error.response.status, error.message);
    }
    return Promise.reject(error);
};
Enter fullscreen mode Exit fullscreen mode

Pros:

  • Resource Efficiency: Token refreshes are triggered only when necessary, conserving system resources and reducing unnecessary network traffic.
  • Simplified Implementation: Reactive token refreshes may require less complex implementation compared to proactive approaches, particularly in scenarios with fewer simultaneous user sessions.

Cons:

  • Potential Delays: Reactive token refreshes may introduce delays in user interactions, particularly if a token expires during an active session, leading to a brief interruption in service.

Conclusion

In a nutshell, mastering token rotation in front-end applications is like keeping a party lively—knowing when to refresh the drinks (tokens) ensures the fun never stops! Whether you prefer to be proactive or reactive, striking the right balance guarantees a secure and smooth user experience. So, let's keep the tokens fresh and the code rockin'!

Top comments (0)