How to send a request to Nodejs backend server when the client closes the browser tab or window?

I am trying to build an application where whenever the client closes the browser window/tab I should send a notification to the backend to destroy the logged-in session and log the details of the running session. I have tried onbeforeunload but it is not working as intended, as it also executes on page reload. Also, it does not send the request by closing the browser tab.