We are going to use AWS Amplify to login to our Amazon Cognito setup. Let’s start by importing it.

Login to Amazon Cognito

The login code itself is relatively simple.

Change indicator Simply replace our placeholder handleSubmit method in src/containers/Login.tsx with the following.

async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    try {
        await Auth.signIn(email, password);
        alert("Logged in");
    } catch (error) {
        // Prints the full error
        console.error(error);
        if (error instanceof Error) {
            alert(error.message);
        } else {
            alert(String(error));
        }
    }
}

Change indicator And import Auth in the header of src/containers/Login.tsx.

import { Auth } from "aws-amplify";

We are doing two things of note here.

  1. We grab the email and password and call Amplify’s Auth.signIn() method. This method returns a promise since it will be logging in the user asynchronously.

  2. We use the await keyword to invoke the Auth.signIn() method that returns a promise. And we need to label our handleSubmit method as async.

Now if you try to login using the admin@example.com user (that we created in the Create a Cognito Test User chapter), you should see the browser alert that tells you that the login was successful.

Login success screenshot

Next, we’ll take a look at storing the login state in our app.