Clear the Session on Logout
Currently we are only removing the user session from our app’s state. But when we refresh the page, we load the user session from the browser Local Storage, in effect logging them back in.
Let’s create a signOutUser
method and add it to our src/libs/awsLib.js
.
export function signOutUser() {
const currentUser = getCurrentUser();
if (currentUser !== null) {
currentUser.signOut();
}
}
Here we are using the AWS Cognito JS SDK to log the user out by calling currentUser.signOut()
.
Next we’ll include that in our App
component. Replace the import { authUser }
line in the header of src/App.js
with:
import { authUser, signOutUser } from "./libs/awsLib";
And replace the handleLogout
method in our src/App.js
with this:
handleLogout = event => {
signOutUser();
this.userHasAuthenticated(false);
}
Now if you head over to your browser, logout and then refresh the page; you should be logged out completely.
If you try out the entire login flow from the beginning you’ll notice that, we continue to stay on the login page through out the entire process. Next, we’ll look at redirecting the page after we login and logout to make the flow makes more sense.
If you liked this post, please subscribe to our newsletter and give us a star on GitHub.
For help and discussion
Comments on this chapterFor reference, here is the code so far
Frontend Source :clear-the-session-on-logout