Building a Serverless Web Application With AWS - Act 1
Tags: awsapigateway, awsamplify, awslambda, amazoncognito
Published: 2022-11-16 15:30:17

If you love unicorns, you're going to love this project I promise you.
Today we will build a simple serverless web application that enables users to request unicorn rides from the [Wild Rydes](http://www.wildrydes.com/) fleet.

Tell me that doesn't sound like fun, haha. 

A serverless architecture is simply a way to build and run applications and services without having to manage infrastructure. Your application still runs on servers, but all the server management is done by your cloud provider, in this case, AWS.

The application architecture we will build in this lab will use:
- AWS Lambda
- Amazon API Gateway
- Amazon DynamoDB
- Amazon Cognito and 
- AWS Amplify Console

### Prerequisites 

To complete this project, you will need: 
- An AWS account
- An account with [ArcGIS](https://www.arcgis.com/home/signin.html) to add mapping to your app
- A text editor and 
- A web browser

_Each service used in this architecture is eligible for the AWS Free Tier. Ensure you follow the recommended configurations throughout the tutorial and terminate all resources within 24 hours.
**Accounts that have been created within the last 24 hours might not yet have access to the resources required for this project.**_

## Use Case
Users of the application would be able to use an HTML based user interface to indicate the location where they would like to be picked up and will interface on the backend with a RESTful web service to submit the request and dispatch a nearby unicorn. The application will also provide facilities for users to register with the service and log in before requesting rides.


![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8ld0emvlgkxvk1xx6a4.png)

## About the Architecture
As earlier mentioned, the application architecture uses AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, and AWS Amplify Console. 

Amplify Console provides continuous deployment and hosting of the static web resources including HTML, CSS, JavaScript, and image files which are loaded in the user's browser. JavaScript executed in the browser sends and receives data from a public backend API built using Lambda and API Gateway. 

Amazon Cognito provides user management and authentication functions to secure the backend API. Finally, DynamoDB provides a persistence layer where data can be stored by the API's Lambda function.

## Configure AWS Amplify

To host the static resources for our web application we will configure AWS Amplify. The Amplify Console provides a git-based workflow for continuous deployment and hosting of full-stack web apps. 

AWS Amplify Console will manage all our static web content including HTML, CSS, JavaScript, images, and other files. End users will then access the site using the public website URL exposed by AWS Amplify Console. 

We won't need to run any web servers or use other services to make the site available.

### Create a Git Repository

We have two options available to us to manage the source code for this module; we can use AWS CodeCommit or GitHub. AWS CodeCommit is included in the AWS Free Tier, I'd be using GitHub for this lab.

If you know nothing about git, you're in luck because today you will use it. Download git for your specific OS from [here](https://git-scm.com/) and install it to follow along.

- a) Create a directory/folder in your computer named "wildrydes-site".
- b) Open the git bash on your computer
- c) Change directory into your repository and Initialize git in that folder to create a local repository.

```hcl
cd wildrydes-site
git init
```

![Image Description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q9fyjmbsi6uxp8debu5w.PNG)

This initializes a local repository in the wildrydes-site folder, if you enable viewing hidden items you will see a .git folder, which indicates that your local repo has been initialized. 

- d) Copy the static files from S3, using the below command:

```hcl
aws s3 cp s3://wildrydes-us-east-1/WebApplication/1_StaticWebHosting/website ./ --recursive
```

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p99or1l7hgxi567t9loc.PNG)

- e) Commit the files to your Git service

```hcl
git add .
git commit -m 'Wildrydes-site'
```

- f) Time to create a remote repo on GitHub. 
     

     1. Go to GitHub
     2. Choose 'New repository' Set the Repository name* to "wildrydes-site". 
     3. Select 'Create Repository' at the end of the page.

- g) Add your GitHub repository as a remote

```hcl
git remote add origin https://github.com/<your GitHub username>/wildrydes-site.git
```

- h) Push the code to your new GitHub repository

```hcl
git push -u origin master
```

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oicu21q9eozb2fr00m2x.PNG)

Note: If this is your first time of using git, you will need to configure your username and email and enter your credentials. This is a good article to put you through [the steps involved](https://linuxize.com/post/how-to-configure-git-username-and-email/).

### Deploy the site with the AWS Amplify Console

Next we’ll use the AWS Amplify Console to deploy the website we just commited to git. The Amplify Console takes care of the work of setting up a place to store your static web application code and provides a number of helpful capabilities to simplify both the lifecycle of that application as well as enable best practices.

- a) Launch the Amplify Console
- b) Scroll to the bottom of the page, underneath Get Started, you’ll find a section titled **"Host your web app"**. Click the Get started button within that section.


![AWS Amplify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3k6uj39rsmax07ke1wff.PNG)

- c) Select GitHub and choose Continue


![AWS Amplify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u39a26e5ezkcm43tfpvc.PNG)

- d) Authorize AWS Amplify, give it the permissions you are comfortable with.

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xr69m685ozedfr31fqzl.PNG)

- e) From the dropdown select the Repository and Master Branch created today and select Next.

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izn6biq2syg5agojqvg1.PNG)

- f) On the "Configure build settings" page leave all the defaults and select Next.

- g) On the "Review" page select Save and deploy

This initial build and deploy process may take up to five minutes for Amplify Console to create the necessary resources and to deploy your code.

Once completed, click the site image to launch your Wild Rydes site.

If you follow the link for Master you’ll see various pieces of information about your website deployment, including sample renderings on various platforms

### Modify the website

The AWS Amplify Console will rebuild and redeploy the app when it detects changes to the connected repository. Let's make a change to the main page to test out this process.

- a) From your text editor, open the index.html file in the /wild-rydes directory of your local repository (the one on your computer).

- b) Modify the title line '<title>wildrydes</title>' so it says:

```html
<title>Wild Rydes - Rydes of the Future!</title>
```
Save the file. 

- c) Commit your changes to your git repository. Use the below codes:

```hcl
git add .
git commit -m 'Modified site Title'
git push
```

![Git CI/CD](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3r2j802knhvgwmqja1a.png)

Amplify Console will begin to build the site again soon after it notices the update to the repository. This happens pretty quickly! Head back to the Amplify Console to watch the process.

- d) Once completed, re-open the Wild Rydes site and notice the title change.

## User Management with Amazon Cognito

Next we'll create an Amazon Cognito user pool to manage our users' accounts. We'll deploy pages that enable customers to register as a new user, verify their email address, and sign into the site.

### Create an Amazon Cognito User Pool

Amazon Cognito provides two different mechanisms for authenticating users. You can use Cognito User Pools to add sign-up and sign-in functionality to your application or use Cognito Identity Pools to authenticate users through social identity providers such as Facebook, Twitter, or Amazon, with SAML identity solutions, or by using your own identity system. For this lab we'll use a user pool as the backend for the provided registration and sign-in pages.

- a) From the AWS Console click Services then select Security, Identity & Compliance, choose Cognito.


![Amazon Cognito](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phj0z5x39c7xhkecy220.png)

- b) Choose Manage your User Pools
- c) Choose Create a User Pool
- d) Provide a name for your user pool such as WildRydes, then select Review Defaults
- e) On the review page, click Create pool
- f) Note the Pool Id on the Pool details page of your newly created user pool.

### Add an App to the User Pool

From the Amazon Cognito console select your user pool and then select the App clients section. Add a new app client and make sure the Generate client secret option is deselected. 

- a) From the Pool Details page for our user pool, select App clients from the left General Settings section in the navigation bar.
- b) Choose Add an app client.


![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dej90er3bcu122u9lsjy.PNG)

- c) Give the app client a name such as WildRydesWebApp.
- d) Uncheck the Generate client secret option. Client secrets aren't currently supported for use with browser-based applications. Keep the default settings for the other options.
- e) Choose Create app client.

![Amazon Cognito](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rqh8zc7folv64goyz22.png)

- f) Note the App client id for the newly created application.

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aptf496okpnbda9bpuct.PNG)

### Update the Website Config

The settings for the user pool ID, app client ID, and Region are present in /js/config.js file. We will update this file with the settings from the user pool and app we created in the previous steps and push it to our repo, from which Amplify would automatically begin to build the site again soon after it notices the update to the repository.

- a) From your local machine, open `wildryde-site/js/config.js` in a text editor of your choice.

- b) Update the cognito section with the correct values for the user pool and app you just created.

You can find the value for userPoolId on the Pool details page of the Amazon Cognito console after you select the user pool that you created.

You can find the value for userPoolClientId by selecting App clients from the left navigation bar. Use the value from the App client id field for the app you created in the previous section.

The value for region should be the AWS Region code where you created your user pool. E.g. us-east-1 for the N. Virginia Region, or us-west-2 for the Oregon Region. If you're not sure which code to use, you can look at the Pool ARN value on the Pool details page. The Region code is the part of the ARN immediately after arn:aws:cognito-idp:.

The updated config.js file should look as below. Note that the actual values for your file will be different:


![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5sntixq6w26ovjw3k4x.png)

- c) Save the modified file and push it to your Git repository to have it automatically deploy to Amplify Console.

```hcl
git add .
git commit -m 'Added Authentication'
git push

```

![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3ll1smw0van9d2uel8s.png)

### Validate your Implementation

Next we will verify that all our hard work in the previous couple of steps actually work. Follow along with the following steps.

- a) Visit /register.html under your website domain, or choose the Giddy Up! button on the homepage of your site.


![Serverless Infrastructure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n849934uhthwdkqq670z.PNG)

- b) Complete the registration form and choose **Create Account**. You can use your own email or enter a fake email. Make sure to choose a password that contains at least one upper-case letter, a number, and a special character. Don’t forget the password you entered for later. You should see an alert that confirms that your user has been created.

⚠️&#9888;&#x26A0; If you get an Authentication Error this is likely because your changes have not finished deploying.

- c) Confirm your new user using one of the two following methods.

- d) If you used an email address you control, you can complete the account verification process by visiting /verify.html under your website domain and entering the verification code that is emailed to you. Please note, the verification email may end up in your spam folder. For real deployments we recommend configuring your user pool to use Amazon Simple Email Service to send emails from a domain you own.

- e) If you used a dummy email address, you must confirm the user manually through the Cognito console.


- f) From the AWS console, click Services then select Cognito under Security, Identity & Compliance.


- g) Choose Manage your User Pools


- h) Select the WildRydes user pool and click Users and groups in the left navigation bar.


- i) You should see a user corresponding to the email address that you submitted through the registration page. Choose that username to view the user detail page.


- j) Choose Confirm user to finalize the account creation process.


- k) After confirming the new user using either the /verify.html page or the Cognito console, visit /signin.html and log in using the email address and password you entered during the registration step.


- l) If successful you should be redirected to /ride.html. You should see a notification that the API is not configured.


![AWS AMplify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjhe9920ifz6gs7qr9bg.png)

So far we have configured and deployed our WebApp on AWS Amplify and used used user pools form AWS Cognito to create a fully-managed user management system that allows us to authenticate our users and manage their user information. 

We updated our website to use the user pool, and used it to provide a signin form on the site. We used Git and GitHub and the functionalities of AWS Amplify for continuous integration and continuous deployment (CI/CD). 

Look at you becoming a total Rockstar!! 

I didn't plan for this post to be this long so we'd be breaking it into series. In the next post in this series we will build a backend process for handling requests for our web application and use Amazon API Gateway to expose the Lambda function you built in the previous module as a RESTful API.

Finally we would terminate all the resources used to throughout this lab avoid being charged.