How to avoid keeping stale user session in idle tabs after logout

Terrence W
2 min readOct 4, 2022

Maintaining up-to-date user session is easy, you can save the session/token in a js variable, in cookie, or in localstorage. However, if a user opens multiple tabs/windows for the same website, some may contain updated data when idle.

For example, a logged-in user opens tab A and B, clicks the logout button in tab A and thus user session is clear on tab A. When he switches to tab B, it still shows his user name or avatar or any protected information. Although the user may not be able to perform any API call in tab B anymore due to session expiry, it may not be a good idea to show stale protected information if the user is logged out.

One way to notify other tabs/windows is through localstorage with event listener.

Let’s recall the memory, saving an item in localstorage is by

window.localStorage.setItem('key', 'value');

This action will fire a storage event automatically. To capture the event, you can add a event listener like this

window.addEventListener('storage', () => {
console.log(window.localStorage.getItem('key'));
});

Note that the event listener won’t trigger on the tab that performs setItem. That means when you set the item on tab A, only tab B will do the console.log.

Full Example

var state = 'LOGGED_OUT';function login() {
// perform login
state = 'LOGGED_IN';
window.localStorage.setItem('state', state);
}
function logout() {
// perform login
state = 'LOGGED_OUT';
window.localStorage.setItem('state', state);
}
window.addEventListener('storage', () => {
var latestState = window.localStorage.getItem('state'));
if (state !== latestState && latestState === 'LOGGED_OUT') {
logout();
}
});

--

--

Terrence W

I am a full stack developer, mainly focus on Nodejs/React.