'Handling Sessions & Idle Timer between multiple tabs in React SPA

I'm developing a React Application that has User Authentication with session duration. while login the response will give session duration with userObject. I'm persisting the loggedUser object using redux-persist in localStorage. I used react-idle-timer to detect the tab idle with sessionDuration I'm getting in loggedUser Object. when user idle reached timeout then, I'll clear the localStorage results user logout.

Here is the Issue I'm facing:

The flow is working exactly for the single tab. when user uses multiple tab. eg, I'm opening a page in the second tab, loggedUser data will be shared using localStorage, here I'm actively using the page. but the first tab gets idle and when the duration exceeds the first tab will be loggedOut by clearing the localStorage, the user who uses second tab actively will be forced to logout, since there is no loggedUser data (localStorage).

How to handle this ?



Solution 1:[1]

Yeh... At starting I was facing the same issue. Your not alone dear. Just add the crossTab property to the code and your problem will be solved.

<div>
  <IdleTimer
    crossTab={true}
    ref={idleTimerRef}
    timeout={1000 * 60 * sessionTimeoutPeriod}
    onIdle={onIdle}></IdleTimer>
</div>

Solution 2:[2]

You can set the crossTab property in IdleTimer component to true.

<IdleTimer
  crossTab={true}
  ref={idleLogoutRef}
  timeout={timeOutLogin * 60 * 1000}
  onIdle={logoutUser}
  onActive={stayActive}
></IdleTimer>

Solution 3:[3]

if not use library, You can subscribe on change events in local storage and refresh the page.

Example:

    window.addEventListener( 'storage', function ( event ) {
    console.log( event.key );
    if ( event.key === 'user_logout' ) {
        window.location.reload();
    }
} );

The event does not fire on the tab that is making the change, but fires on the rest of the domain's tabs in the browser.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ishaiknadeem
Solution 2 Pamungkas Gumilang Aji
Solution 3