I have a web chat application made with NextJS, and I wanna kick the user from chat when close tab, but no action when user refresh tab. How can I achieve this? There has to be a solution for mobile too?
If you have a chat app, you’re almost certainly using websockets. Kick the user from chat (say) a minute after their socket closes if they have no other active sockets.
On the server, monitor the opening and closing of websockets for each user. When a user opens a websocket, associate that socket with the user in the server’s memory. When a user closes a websocket (which could be a result of either the user closing the page/browser, or refreshing their page), check if they have any other active sockets. If not, set a timeout for, say, a minute from now. When that minute is up, check if the user still has no active sockets. If not, then they haven’t refreshed the page; they’ve closed it completely, so kick them. If so, then they’ve reconnected and shouldn’t be kicked.
Also clear the timeout associated with the user any time that user connects a new websocket.
Answered By – CertainPerformance
Answer Checked By – Dawn Plyler (Easybugfix Volunteer)