User logout on tab/window close

We are building a React application with the auth0 SDK closely following this tutorial. The basic loginWithRedirect, withAuthenticationRequired and logout functions all work as expected.

Since we are dealing with sensitive data in our app we want to make sure to log users out of their session when they close the application tab or the browser window.

To start with, in the Login Session Management settings we make sure to select a Non-Persistent Session, and we set “Inactivity Timeout” and “Require log in after” relatively low.
As mentioned here, this is not enough to trigger a logout for tab closes and neither for all cases of browser closes.

One workaround I have found discussed here and elsewhere in the forum is to use an event handler for beforeunload which calls the logout function (i.e. implements a redirect to the logout endpoint):

const { logout } = useAuth0();

  useEffect(() => {
    function handleBeforeUnload(event: BeforeUnloadEvent) {
      event.preventDefault();
      event.returnValue = '';
      logout({ logoutParams: {returnTo: window.location.origin} });
      return '';
    };
    
    window.addEventListener('beforeunload', handleBeforeUnload, {capture: true});

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload, {capture: true});
    };
  }, []);
  

However, this is not a reliable solution and causes unexpected behaviour (e.g. me reaching the rate limit).

I would appreciate any help with implementing this “logout on tab close” behaviour correctly!

Hello @david47!

Using Non-persistent sessions will give you the desired result. Here are some docs that explain how they work in Auth0. Please give this a read

I hope this helps!

Best,
Alex