How To Keep user logged in on refresh but log out on browser/tab close in Angular?

Discussão em 'Angular' iniciado por Onjomba Felix, Setembro 6, 2025.

  1. How can i make my angular application maintain the user session on page refresh but automatically log out the user when the browser tab or windows is closed?

    What I Tried


    1. I used the beforeunload event in Angular (window.addEventListener('beforeunload', …)) to know when the tab is closing.


    2. I called my authService.logout() inside this event to log the user out.


    3. But I noticed this also runs when the page refreshes or when the user navigates away, which I don’t want.


    4. I also checked the MDN docs and tried using returnValue for the unload event, but it shows the generic browser message and still activates on refresh.

    What I Expected


    1. When the user refreshes the Angular page, the session/token should be kept so they remain logged in.


    2. When the user closes the browser or tab, the app should log them out automatically, clearing tokens/session both locally and on the backend.

    Continue reading...

Compartilhe esta Página