'Session expired functionality for MERN stack project

I want to implement session expire functionality. so when the user stays on that page for more than 15 min then it should show an alert that the session is expired now. also, meanwhile, if someone copies that URL and pastes it to another tab/browser/incognito (where he was already logged in) or refreshes the page, it should not retake the countdown. for example, if it's in the middle of the countdown let's say 5 min left to reach 15min then after copy-pasting URl on another tab at that time it should start from 5min left then 4 min left, and so on without retaking the countdown from 15 min. I am not sure what is the best way to implement this in the MERN stack project (should use any library or cookie or local storage) also with security?

I tried sample implementation but it does not work for cross-browser or for incognito it retakes the session also after 15min if I refresh the page countdown timer again starts. someone has a better example or suggestion regarding how to implement the functionality is really appreciated TIA :-) My dummy implementation example - countdowntimer.tsx file

    const history = useHistory();
    const [countdownSessionExpired, setCountdownSessionExpired] = React.useState(false);

    React.useEffect(() => {
        const countDownTime = localStorage.getItem(COUNTER_KEY) || 10;
            countDown(Number(countDownTime), () => {
                console.log("countDownTime:", countDownTime);
                setCountdownSessionExpired(true);
            });
    }, [history]);
    return (
        <>
            {countdownSessionExpired ? (
                <div>sessoin is expired</div>
            ) : (
                 <div>view the page</div>
            )}
        </>
    );
};

==================================================================================================

countdowntimer.utils.tsx file

export const COUNTER_KEY = "myCounter";

export function countDown(i: number, callback: Function) {
    const timer = setInterval(() => {
        let minutes = i / 60;
        let seconds = i % 60;

        minutes = minutes < 10 ? 0 + minutes : minutes;
        seconds = seconds < 10 ? 0 + seconds : seconds;

        // document.getElementById("displayDiv")!.innerHTML = "Time (h:min:sec) left for this station is  " + "0:" + minutes + ":" + seconds;
        console.log("Time (h:min:sec) left for this station is:", seconds, i--);
        if (i-- > 0) {
            localStorage.setItem(COUNTER_KEY, String(i));
        } else {
            localStorage.removeItem(COUNTER_KEY);
            clearInterval(timer);
            callback();
        }
    }, 1000);
}```


Sources

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

Source: Stack Overflow

Solution Source