Session Timeout in SPAs
After converting an old JSP multi-page app to a React SPA (single-page app) I find that the session-timeout functionality no longer works the same. In a traditional multi-page app, the user’s login session (aka whether the user’s login has timed out) is managed on the server-side. Thus the user’s session is naturally validated whenever the user navigates from page to page. If his login session has timed out, the user is redirected to a login page.
But in an SPA, navigating from page to page may not necessarily hit the server. Thus, in an SPA, the only time session’s are validated is when making an AJAX call to the server.
Thus, someone could walk away from their system. And two hours later, they are still able to navigate from page to page (assuming they don’t make any ajax calls). Even though the server-side session has long since expired.
So here is how I decided to handle session-timeout in my SPA:
First of all, I always check the returned http status code on all of my ajax calls. If 401 (unauthorized) is returned, I prompt the user to re-login.
Here is the logic I use to make sure the user can’t not page around after his server-side session has timed out.
- I set my server-side session timeout (max inactivity interval) to 30 min.
- I setup a 31 min client-side timer that runs on app startup and resets whenever client navigates from page to page.
- When the 31 minutes is up, I make a call to the server to see if our session is still alive. If no, I set a client-side variable called isLoggedIn to false. If yes, I set isLoggedIn to true and reset the timer.
- Then when the user tries to navigate to a new page, I check the isLoggedIn flag. If isLoggedIn=true, I reset the timer. If isLoggedIn=false, I redirect the user to the login page.