Voiced by Amazon Polly |
Overview
In my previous blog, we learned how to verify the user in the Cognito user pool and how to log in the user in our application using ‘amazon-cognito-identity-js’. In this blog, we will learn how to manage the state or session of a logged-in user and how to log out the user from the application using the ‘amazon-cognito-identity-js’ library.
Freedom Month Sale — Upgrade Your Skills, Save Big!
- Up to 80% OFF AWS Courses
- Up to 30% OFF Microsoft Certs
Introduction to 'amazon-cognito-identity-js'
‘amazon-cognito-identity-js’ is the SDK that allows a JavaScript-enabled application to authenticate the users, view user details, delete users, update users and register the users. It also allows password change for authenticated users and forgot password functionality.
Steps to Create a Component
Step 1: Create an Account.js file in src/Components directory and follow the code snippet in the file.
This code snippet is for Central session management. We can use it in every component. In this component, we will get the current session information using getCurrentUser method in getSession function. And in authenticating function, we will authenticate the user. And Logout function is to log out the user from the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import { AuthenticationDetails, CognitoUser } from 'amazon-cognito-identity-js'; import { createContext } from 'react'; import UserPool from '../UserPool'; const AccountContext = createContext(); const Account = (props) => { const getSession = async () => { await new Promise((resolve, reject) => { const user = UserPool.getCurrentUser(); if (user) { user.getSession((err, session) => { if (err) { reject(err); } else { resolve(session); } }); } else { reject(); } }); }; const authenticate = async (Username, Password) => { await new Promise((resolve, reject) => { const user = new CognitoUser({ Username, Pool: UserPool, }); const authDetails = new AuthenticationDetails({ Username, Password, }); user.authenticateUser(authDetails, { onSuccess: (result) => { console.log('login success', result); resolve(result); }, onFailure: (err) => { console.log('login failure', err); reject(err); }, newPasswordRequired: (data) => { console.log('new password required', data); resolve(data); }, }); }); }; const logout = () => { const user = UserPool.getCurrentUser(); user.signOut(); window.location.href = '/'; }; return ( <AccountContext.Provider value={{ authenticate, getSession, logout }}> {props.children} </AccountContext.Provider> ); }; export { Account, AccountContext }; |
Step 2: Create a ‘Status.js’ file in src/components directory
This code snippet is to get the user’s current session using the getSession function which we created in the last step. And on the UI, we are displaying the current status of the user using HTML code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { useContext, useEffect, useState } from 'react'; import { AccountContext } from './Account'; const Status = () => { const [status, setStatus] = useState(false); const { getSession, logout } = useContext(AccountContext); useEffect(() => { getSession() .then((session) => { console.log('Session: ', session); setStatus(true); }) .catch((err) => { console.log('Session: ', err); setStatus(false); }); }, [status]); return ( <div> {status ? ( <div> {' '} You are logged in. <button onClick={logout}>Logout</button> </div> ) : ( 'Please Login' )} </div> ); }; export default Status; |
Step 3: Modify the App.js
This code snippet is for wrapping the whole application with the Account component to use all the function of the Account component in every component of the application.
<Status /> is to display the current stage of the user whether it is logged in or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { BrowserRouter, Route, Routes } from 'react-router-dom'; import './App.css'; import { Account } from './Components/Account'; import Login from './Components/Login'; import Register from './Components/Register'; import Status from './Components/Status'; function App() { return ( <Account> <Status /> <BrowserRouter> <Routes> <Route path="/" element={<Login />} /> <Route path="/register" element={<Register />} /> <Route path="/login" element={<Login />} /> </Routes> </BrowserRouter> </Account> ); } export default App; |
Step 4: Modify the Login.js file
In this step, we are modifying the login page and will call authenticate method of the Account component to log in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import { useContext, useState } from 'react'; import { AccountContext } from './Account'; function Login() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const { authenticate } = useContext(AccountContext); const onSubmit = (e) => { e.preventDefault(); authenticate(username, password) .then((data) => { console.log(data); alert('login success'); window.location.reload(); }) .catch((err) => { console.log(err); alert('login failure'); }); }; return ( <div> <form onSubmit={onSubmit}> Username: <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> Password: <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type="submit">Login</button> </form> </div> ); } export default Login; |
Conclusion
In this blog, we learn how to manage the state or session of logged in users and how to log out the user from the application using the ‘amazon-cognito-identity-js’ library.
In my next blog, we will see how to implement change password functionality in our application.
Freedom Month Sale — Discounts That Set You Free!
- Up to 80% OFF AWS Courses
- Up to 30% OFF Microsoft Certs
About CloudThat
CloudThat is an award-winning company and the first in India to offer cloud training and consulting services worldwide. As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, and Google Cloud Platform Partner, CloudThat has empowered over 850,000 professionals through 600+ cloud certifications winning global recognition for its training excellence including 20 MCT Trainers in Microsoft’s Global Top 100 and an impressive 12 awards in the last 8 years. CloudThat specializes in Cloud Migration, Data Platforms, DevOps, IoT, and cutting-edge technologies like Gen AI & AI/ML. It has delivered over 500 consulting projects for 250+ organizations in 30+ countries as it continues to empower professionals and enterprises to thrive in the digital-first world.
FAQs
1. Can we display the logged-in user’s username or email?
ANS: – Yes, we can display the user information on the page. Once the user is logged in, we will get the user information as a JSON object from the AWS Cognito User Pool. by parsing the JSON object, we can display the user information on the page.
2. Can we redirect the user to login page after logout?
ANS: – Yes, we can redirect the user to the login page once the user is logged out from the application. We can use navigate or normal javascript method (window.location.href)

WRITTEN BY Mayur Patel
Mayur Patel works as a Lead Full Stack Developer at CloudThat. With solid experience in frontend, backend, database management, and AWS Cloud, he is a versatile and reliable developer. Having hands-on expertise across the entire technology stack, Mayur focuses on building applications that are robust, scalable, and efficient. Passionate about continuous learning, he enjoys exploring new technologies daily and actively shares his knowledge to foster growth within his team and the broader community. Mayur’s practical approach, strong teamwork, and drive for innovation make him an invaluable member of every project he undertakes.
Comments