I have a React application with a login mechanism that stores the user’s authentication token in localStorage. Here’s the issue I am facing:
- User “A” logs in (tab 1).
- User “A” opens a new tab (tab 2); they remain logged in as user “A”.
- In tab 2, the user logs out and logs back in as user “B”. The token in localStorage updates to the one for user “B”.
- When the user returns to tab 1, they see user “B”‘s data loaded in the UI, but the token in localStorage was originally for user “A”.
The problem seems to arise because localStorage is shared between tabs, so the token gets overwritten across all tabs. At the same time, I cannot use sessionStorage because I want the user to maintain authentication if they open a new tab.
My Questions:
-
What is the best practice to handle this kind of issue?
-
Should I implement a polling mechanism to sync tabs?
-
Are there any alternatives to localStorage that allow syncing across tabs but avoid this conflict?
I’d appreciate any insights or suggestions on this. Thanks!
2