Middle
If requests are not made for some time and the token expires, what happens then? Have you looked at token lifetime through a timer?
sobes.tech AI
Answer from AI
If the token expires due to lack of requests, the server will return an authorization error (usually 401 Unauthorized) on the next attempt to access a protected resource. In this case, the frontend should initiate the token refresh process or redirect the user to the login page.
Using a timer to track the token's lifetime is a common practice. For example, when receiving a token, you can store its expiration time and start a timer that automatically refreshes the token a few minutes before expiration to avoid session interruption.
Example of using a timer in JavaScript:
const tokenExpiryTime = Date.now() + tokenExpiresIn * 1000; // expiration time in ms
setTimeout(() => {
refreshToken(); // token refresh function
}, tokenExpiresIn * 1000 - 60000); // refresh 1 minute before expiration
Thus, the user will not face an unexpected logout.