'AWS Cognito + aws-amplify: session state always keep user logged in?

I'm using AWS Cognito and aws-amplify to manage user authentication. When I load up my app, I call Auth.currentSession() which seems to always return the user I was logged in as if I do not explicitly log out by calling Auth.signOut().

I'm fine with this should the user choose a "keep user logged in", but if they don't, how would I go about making sure the user gets logged out once they leave the app?

I tried adding an event listener in my login() method but that didn't work i.e. the user was still logged in when I returned to the app:

.
.
.

if (!keepSignedIn) {
    window.addEventListener('unload', function(event) {
        Auth.signOut();
    });
}


Solution 1:[1]

I'm pretty sure the logout() method creates a promise - it operates asynchronously. So the page is probably being destroyed before the promise's logout code is executed.

You can confirm this by executing console.log(Auth.signOut());. If it's a promise it'll log Promise { <pending> }

There's no way to halt unloading of the page, as that would be bad if we could.

What you need is a synchronous signout function. Fortunately, you can just clear the browser local storage, which is a synchronous operation. (Local storage is where Amplify stores the auth tokens.)

if (!keepSignedIn) {
  window.addEventListener('unload', function(event) {
    localStorage.clear();
  });
}

Depending on your situation you may need to instead find and remove individual local storage items, instead of clearing them all.

Solution 2:[2]

You can clear Amplify cache before Auth.signOut()

import AmplifyCache from '@aws-amplify/cache';

AmplifyCache.clear();

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 jameslol
Solution 2 grzly