Multi Tab Logout in React — Redux
Single Page Applications are common these days, they are everywhere. Maintaining authentication state is a must in most of the web apps.
The usual method in a React-Redux application is to have an auth state in the store and save a token in localStorage. When a user logs in, we save the token from the API response and when the user logs out we delete the token from local storage.
It seems all easy but there is a challenge when it comes to logout, if the user has opened multiple tabs and logs out from one tab then other tabs should be logged out too. But other tabs won’t notice the change until the user try to do any api related action, then the API will return 401 stating its an unauthorized request and logs out the user if the token is not found in our local storage.
There is a neat little way to log out all the tabs if the user clicks logout from one tab. Since we will be maintaining a token in localStorage. We can add an event listener for our storage and check if the token becomes null then, we’ll dispatch a logout action to logout the user from all the open tabs.
For each change in our localStorage, we will get a storage event emitted and we can check the event params to see if the key is our token and it has an old value and if the new value is empty, we can dispatch a user sign out action to logout the user
More Resources:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API