How to implement Forgot Password AWS Cognito: React/Angular/ Vanilla JS
In this article, we will implement the flow to reset the user’s password through OTP. We will be using the React as our client but the code will be remain almost similar for any other JavaScript framework.
Prerequisites:
1. Basic Understanding of JavaScript
2. Basic Understanding of React JS
3. AWS account and Cognito configs
Step — 1: Create a React Project
I believe you have NodeJS already installed in your system, If not then install the NodeJS.
Run this command on your favorite terminal. This will start the app on localhost:3000
npx create-react-app my-example
cd my-example
npm start
Step — 2: Install the Required Dependency
npm i aws-amplify
Step — 3: Initialise the AWS Config.
try {
Amplify.configure({
Auth: {
userPoolId: //Enter the userPoolID,
region: //Enter the region of AWS,
userPoolWebClientId: //Enter the webclient ID
}
});
} catch (error) {
console.log(error)
}
Step — 4: Forgot Password Code
Before implementing the Forgot Password, you need to implement the Login/SignIn flow, if you are confused through that you may find this link helpful to implement the link.
Now after login you need to call this “forgotpassword” function.
forgotpassword(username){
Auth.forgotPassword(userName).then((value)=>{
console.log(value)).catch((error)=>{
console.log(error)})
}
User will get the OTP on the verified medium (Mobile/ Email)
Final Step: Confirm Password Code
confirmForgotPassword(username,otp,newpassword){
Auth.forgotPasswordSubmit(username,otp,newpassword)
.then((value)=>{console.log(value))
.catch((error)=>{console.log(error)})
}
Ask the user to enter the OTP and New Password and pass the values to “confirmForgotPassword” function.
Thank you for reading, if you find this story useful give it a clap. It's always great to read from Documentation, so to read more about the functionality click here.