paint-brush
How to Set Up Authentication With AWS Amplify in Nextby@terieyenike
2,344 reads
2,344 reads

How to Set Up Authentication With AWS Amplify in Next

by TeriSeptember 6th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

AWS Amplify is a tool that lets frontend web and mobile developers build and deploy full-stack applications on AWS. We will add the auth feature of Amplify to an already existing front-end web crypto app. The app will allow users to sign in to see the latest crypto prices after signing up. The code for implementing the feature in the next-gen branch of the app is this GitHub branch auth repo. We use the useAuthenticator composable to access the current user signed in during sign-up.
featured image - How to Set Up Authentication With AWS Amplify in Next
Teri HackerNoon profile picture

Authentication is a way for applications to confirm user identity before granting permission or entry to a website. In this way, a user must prove their identity through a username, password, email, and so on. 

What is AWS Amplify?

AWS Amplify is a tool that lets frontend web and mobile developers build and deploy full-stack applications on AWS. Using AWS Amplify, it integrates with various libraries and frameworks.

In this article, we will add the auth feature of Amplify to an already existing frontend web crypto app, allowing users to sign in to see the latest crypto prices after signing up. One more feature of the app is the sign-out feature.


Prerequisites

The following setup is required to complete this post:

  • AWS account. Sign up for a free account
  • Node >= 14.0.0 and npm >= 5.6 installed on your local machine
  • A code editor (VS Code recommended)
  • Install the AWS Amplify CLI. Run this command, npm i -g @aws-amplify/cli
  • Knowledge of JavaScript and React

Use this GitHub repo to get the complete source code for this post.

Check out the live demo of the crypto application

Getting Started

Since we will not be building the crypto web app, clone the starting main branch.

Run this command:

git clone --branch main [email protected]:Terieyenike/react-nextjs-crypto-tracker.git

Once done, change the directory and run this command to install its dependencies:

npm install

To start the development server on

http://localhost:3000
to confirm the app is working, run:

npm run dev


The app should look like this:

Next, let’s set up Amplify for the project and create a named profile:

Setting up Amplify

In the root of the project’s directory, we need to initialize amplify in the project. Run this command which will create a new folder called amplify:

amplify init

Follow the prompts with these selected options:

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project nextjsamplifyauth
The following configuration will be applied:

Project information
| Name: nextjsamplifyauth
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react
| Source Directory Path: src
| Distribution Directory Path: build
| Build Command: npm run-script build
| Start Command: npm run-script start

? Initialize the project with the above configuration? Yes
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Please choose the profile you want to use

With the guidelines followed above, the success message should look like this:

CREATE_COMPLETE amplify-nextjsamplifyauth-dev-104950 AWS::CloudFormation::Stack Tue Aug 30 2022 10:50:23 GMT+0100 (West Africa Standard Time)
✔ Successfully created initial AWS cloud resources for deployments.
✔ Help improve Amplify CLI by sharing non sensitive configurations on failures (y/N) · yes

✔ Initialized provider successfully.
✅ Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

In the installed amplify directory, the file structure should be like this:

Let’s now add the authentication service to our Next application.

Creating the Authentication Service

Still, in the project’s root folder, run the following command:

amplify add auth

This command adds authentication to the backend configuration with these prompt options:

Using service: Cognito, provided by: awscloudformation

 The current configured provider is Amazon Cognito.

 Do you want to use the default authentication and security configuration? Defau
lt configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
✅ Successfully added auth resource nextjsamplifyauthd76ad210 locally

The installation successfully adds the auth/nextjsamplifyauthd76ad210 to the amplify backend folder. Now, let’s deploy the service to amplify cloud with the push command:

amplify push

The deployed message logs should look like this:

UPDATE_COMPLETE                     amplify-nextjsamplifyauth-dev-104950 AWS::CloudFormation::Stack Tue Aug 30 2022 11:07:18 GMT+0100 (West Africa Standard Time)
✔ All resources are updated in the cloud

To check the deployed auth service in the AWS Amplify Studio, it should look something like this:

The deployment to amplify studio is complete, and it works. Let’s start wiring up our app with AWS auth in Next.

Setting up Auth in Next

To integrate the auth service to the Next application, we must install the Amplify UI components necessary for styling the demo app and the dependency

aws-amplify
for configuration.

Run this command:

npm install @aws-amplify/ui-react aws-amplify

Update the entry point of the app,

index.js
, with the following code:

// pages/index.js

import {useState} from 'react';

// other imports

import Layout from '../sections/Layout';

// add this
import {
    useAuthenticator,
    withAuthenticator,
    Button,
    Flex,
    Heading
} from '@aws-amplify/ui-react';
import {Amplify} from 'aws-amplify';
import '@aws-amplify/ui-react/styles.css';
import awsExports from "../src/aws-exports";

Amplify.configure(awsExports)

const Home = ({filteredCoins}) => {
    const {user, signOut} = useAuthenticator((context) => [context.user]);

    // allCoins method with callback function to include search of the coins

    // handleChange method

    return (
        <div>
            <Layout>
                <Flex direction={"row"} justifyContent="center" alignItems="center">
                    <Heading level={3} color="neutral[100]" fontWeight="bold">Welcome, {user.username}!</Heading>
                    <Button fontWeight='normal' onClick={signOut} size='small'>
                        Sign Out
                    </Button>
                </Flex>

                // filtered coin list

            </Layout>
        </div>
    );
}

export default withAuthenticator(Home) // add this

// data fetching with getServerSideProps

In the code, the following occurs:

  • Import the
    Authenticator
    component that adds complete authentication flows
  • The
    aws-amplify
    , the import package, is a JavaScript library for building cloud-enabled applications.
  • The UI React package is a customized theme like every other CSS utility, meant for styling a project.
  • Next, we use the imported
    aws-exports
    file and configure it with Amplify.
  • The
    useAuthenticator
    composable can access the current user signed in during sign-up.
  • The rest of the file handles the components like Flex, Heading, and Button that take care of how the app appears on the page with its CSS properties.
  • In the
    <Heading>
    component, the user object is assigned to the username. 
  • On the
    <Button>
    component, we use the onClick event and assign the field's value from the
    context.user
    object
  • Finally, to get the app working with authentication, wrap the app with the higher-order component (HOC),
    withAuthenticator()

That’s it. The app should work as expected, as shown:





The complete source code for implementing authentication in Next with AWS Amplify is in this GitHub feature branch auth repo.

Conclusion

In this article, we learned how to configure and set up a working authentication in our Next application without needing a lot of complex setups and writing logic backend code.