• About Us
  • Blogs
  • Contact Us
How To Build a Serverless Web Application - Part A

Overview

In this guide, we will create a serverless web application. The purpose of this application includes allowing the users to make a request for unicorn rides from the Wild Rydes fleet. Moreover, this application will present an interface (HTML-based) to the users for informing about the location where they would like to be picked up. It will also communicate with the RESTful web services for submitting the request and dispatching a nearby unicorn. Lastly, the users will have to register or perform a login before requesting rides.

Prerequisites

Following prerequisites must be considered to move forward in this tutorial.

  • AWS account
  • AWS CLI
  • ArcGIS account (to add mapping)
  • Text Editor
  • Web Browser

Application Architecture

This web application will make use of the following AWS services.

Although each and every service holds its own importance but let us continue the discussion with AWS Amplify Console. So what actually Amplify console does? Well, it provides continuous deployment and hosting of the static web resources. This includes HTML, CSS, JS and image files to be loaded in the browser.

Lambda and API Gateway helps in building a public backend API which will be used by JavaScript (the one executed in the browser) to send and receive data. As far as Amazon Cognito is concerned, it will mostly deal with user management and authentication to secure the backend API. At last, DynamoDB will be used to store data.

Modules

This tutorial is divided into 5 modules which are as follows.

  1. Host a Static Website
  2. Manage Users
  3. Build a Serverless Backend
  4. Deploy a RESTful API
  5. Terminate Resources

Module 1 – Host a Static Website

Overview

In this particular module, you will use AWS Amplify for hosting static resources for your application with continuous deployment (built-in). The continuous deployment and hosting of web apps is made possible because Amplify Console provides users with a git-based workflow. In other modules, you will be allowed to add dynamic functionality to the pages.

Architecture Overview

There is nothing too complex when it comes to the architecture of this module. All the static web content of your application will be fully managed by Amplify Console. It will expose a public URL which will be used by the users for accessing your site. There is no need to run additional services or web servers to ensure the availability of your site. In case of real applications you will want to use a custom domain for hosting your site. If you want it then you can follow the procedure of setting a custom domain on Amplify.

Implementation

Follow the implementation steps carefully to avoid any inconvenience.

Select a Region

The important thing to note here is that your web application will be deployed only in that AWS region which shows support for all services used in this application. For this purpose, you can consider the AWS Regional Services List. Some of the supported regions are:

  • US East (N. Virginia)
  • US East (Ohio)
  • US West (Oregon)
  • EU (Frankfurt)
  • EU (Ireland)
  • EU (London)
  • Asia Pacific (Tokyo)
  • Asia Pacific (Seoul)
  • Asia Pacific (Sydney)
  • Asia Pacific (Mumbai)

You can select your region from the dropdown menu present in the upper right corner of AWS Management Console.

Create a Git Repository

You will be provided with two options for managing the source code; AWS CodeCommit or GitHub. In this particular tutorial, we will use CodeCommit to store the application code.

  • Start by configuring the AWS CLI on your machine. You will need a terminal window for installing AWS CLI. The installation instructions for every operating system will be different. If you have already configured the CLI then move to the next step.
  • Navigate and open AWS CodeCommit console.
  • Choose “Create Repository” option.
  • Write “wildrydes-site” as the repository name and choose “Create” option.
  • Now set up IAM user with Git credentials in the IAM console. Navigate to the page: Setup for HTTPS users using Git credentials and keep following the instructions mentioned in step 1 to step 3.
  • Create access keys in the “Security Credentials” tab and save them or download them in a secure location. Along with this, generate HTTPS Git credentials for AWS CodeCommit.
  • Open the terminal window that you used for the installation of AWS CLI and type the following command: aws configure
  • Enter the Secret Access Key and AWS Access Key ID that you created in step 6.
  • Enter the region name that you initially selected to create the CodeCommit repository in.
  • Leave the output format blank and hit Enter.

You will see the following code block in your terminal window:

% aws configure

AWS Access Key ID [****************]: #####################

AWS Secret Access Key [****************]: ###################

Default region name [us-east-1]: us-east-1

Default output format [None]:
  1. It is time to set up the git config credential helper in the terminal window.
  2. For Linux, macOS or UNIX, go through step 3: Setting up the credential helper instructions.
  3. For Windows go through step 3: Setting up the credential helper instruction.
git config --global credential.helper '!aws codecommit credential-helper $@'

git config --global credential.UseHttpPath true
  • Select the wildrydes-site repository by navigating back to the AWS CodeCommit console.
  • Expand the Clone URL dropdown menu and select Clone HTTPS.  Copy the HTTPS URL.
  • Go back to your terminal window and run “git clone” and also paste the HTTPS URL that you just copied in the previous step.

You will see the following code block in your terminal window.

$ git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/wildrydes-site

Cloning into ‘wildrydes-site’...

Username for ‘https://git-codecommit.us-east-1.amazonaws.com/v1/repos/wildrydes-site’: Enter the HTTPS Git credentials for AWS CodeCommit username you generated in steps above

Password for ‘https://username@git-codecommit.us-east-1.amazonaws.com/v1/repos/wildrydes-site’: Enter the HTTPS Git credentials for AWS CodeCommit password you generated in steps above

warning: You appear to have cloned an empty repository.

It is expected that you might receive a warning saying that you have cloned an empty repository. To deal with such common errors, visit the following guide.

Troubleshooting the credential helper and HTTPS connections to AWS CodeCommit

Populate the Git Repository

After successfully creating your Git repository (either by GitHub or AWS CodeCommit) and cloning it locally you now need to add the content to your repository by copying them from an existing and publicly accessible S3 bucket.

  • Navigate to your repository by changing the directory. Copy the static files from S3 bucket with the help of the following commands.
cd wildrydes-site

aws s3 cp s3://wildrydes-us-east-1/WebApplication/1_StaticWebHosting/website ./ --recursive
  • Add, commit and push the Git files.
$ git add .

$ git commit -m "new files"

$ git push

You will see the following code block in your terminal window.

Counting objects: 95, done.

Compressing objects: 100% (94/94), done.

Writing objects: 100% (95/95), 9.44 MiB | 14.87 MiB/s, done.

Total 95 (delta 2), reused 0 (delta 0)

To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/wildrydes-site

* [new branch] master -> master

Enable Web Hosting with the AWS Amplify Console

The next step is the deployment step. You will deploy the website by using AWS Amplify Console. For this you need to follow the following steps.

  1. Open AWS Amplify console.
  2. Click on the option “Get Started”.
  3. Look for “Amplify Hosting Host your Web App” Header and choose the option “Get Started”.
  4. Choose “AWS CodeCommit” and select “Continue” option.
  5. Now comes the add repository branch step. Here you need to select the repository having the name “wildrydes-site”.
  6. Authorize AWS Amplify to your GitHub account in case you are using GitHub.
  7. Select the “master” branch from the branch dropdown menu and choose “Next”.
  8. Leave all the options to default when you come on the Build Settings page. Select “Allow AWS Amplify to automatically deploy all files hosted in your project root directory” and then choose “Next”.
  9. As soon as you land on Review page, select “Save and Deploy”.
  10. Wait for a few minutes to allow Amplify Console to create necessary resources and deploy the code.

To launch your very own Wild Rydes site, either select the site image or click on the link present underneath the thumbnail.

Modify your Site

As soon as AWS Amplify console detects changes to the connected repository, it will rebuild and redeploy the web app. To test it out, make a change to the main page.

  1. By staying on your local machine, visit the wildrydes-site folder and open the index.html file in any text editor.
  2. Modify the title by changing it to “Wild Rydes – Rydes of the Future!”
  3. Save the file after making the changes.
  4. Through your terminal window, you now need to add and commit the changes and then push the change to the repository. Amplify Console will rebuild the site after this change has been detected.

You will see the following code block in your terminal window.

$ git add index.html

$ git commit -m "updated title"

[master dfec2e5] updated title

 1 file changed, 1 insertion(+), 1 deletion(-)

$ git push

Counting objects: 3, done.

Compressing objects: 100% (3/3), done.

Writing objects: 100% (3/3), 315 bytes | 315.00 KiB/s, done.

Total 3 (delta 2), reused 0 (delta 0)

remote: processing

To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/wildrydes-site

   2e9f540..dfec2e5  master -> master
  • After the redeployment process has successfully completed, open the site again and see the change for yourself.

Module 2 – Manage Users

Overview

This module is related to the user management. You will create a user pool by using Amazon Cognito to manage the accounts. Pages like sign up and sign in will be deployed as well.

Architecture Overview

The first thing that users need to do when they visit your website is to create a user account by providing email and password. If you want to include additional attributes in your application then you can use Amazon Cognito for this. After submitting their registration, the users will receive a confirmation email (on the provided email) containing verification code. Users will have to navigate back to the site and enter their email along with the verification code. The users should be able to perform a sign in after confirming their account. Users will have to provide email and password whenever they want to perform a sign in. During this process, a JavaScript function communicates with Amazon Cognito for authentication. It uses SRP – Secure Remote Password Protocol and receives a set of JWT – JSON Web Tokens. These web tokens will play a great role in maintaining the identity of the users.

Implementation

Follow the implementation steps carefully to avoid any inconvenience.

Create an Amazon Cognito User Pool and Integrate an app with your User Pool

There are two mechanisms that Amazon Cognito provides for the authentication purpose. You can either use Cognito User Pools to include sign in and sign up functionality to the application or you can also use Cognito Identity Pools for authenticating the users through social identity providers. We will be using a user pool for this module.

  1. Go to Amazon Cognito console and select “Create User Pool” option.
  2. In the sign-in options section of Cognito user pool, select the username. Leave all other options to default and select “Next”.
  3. You will see Password policy mode on the “Configure security requirements page”, keep the mode as Cognito defaults. You can also choose multi-factor authentication or No MFA while keeping other configurations as default. Then choose “Next”.
  4. On the “Configure sign-up experience page”, leave all the things to be default and select “Next”.
  5. Next, on the “Configure Message Delivery Page” confirm that “Send email with Amazon SES – Recommended” is selected for email provider. Similarly, in the “FROM” email address field, use that email address which you have already verified with Amazon SES by following the instructions in Verifying an email address identity in Amazon Simple Email Service Developer Guide.
  6. On the integration page, name your user pool to be “WildRydes”. Along with this, name the app client to be “WildRydesWebApp” while leaving other settings to default.
  7. Choose “Create User Pool” option on the “Review and Create Page”.
  8. On the “User Pools Page”, copy the User Pool ID and save it locally on your machine.
  9. Navigate to “App Integration” tab, copy and save the Client ID.

Update the Website Config File

If you want to access the settings of pool ID, app client ID and region then you can see js/config.js file. Update this file with the settings of user pool and app that you just created in the previous steps. After doing this, upload the file back to the bucket.

  • Open the file “wildryde-site/js/config.js” in any text editor.
  • Update the Cognito section present in the file with the values of User Pool ID and App Client ID that you saved in the previous section.
  • AWS Region code (where you created the user pool) should be the value for region.

The updated code in the config.js file will look like this.

window._config = {

    cognito: {

        userPoolId: 'us-west-2_uXboG5pAb', // e.g. us-east-2_uXboG5pAb

        userPoolClientId: '25ddkmj4v6hfsfvruhpfi7n4hv', // e.g. 25ddkmj4v6hfsfvruhpfi7n4hv

        region: 'us-west-2' // e.g. us-east-2

    },

    api: {

        invokeUrl: '' // e.g. https://rc7nyt4tql.execute-api.us-west-2.amazonaws.com/prod',

    }

};
  • Save the file.
  • In your terminal window, add and commit the changes and push the file to your repository.

You will see the following code block in your terminal window.

$ git add .

$ git commit -m "new_config"

$ git push

Validate your Implementation

  1. Navigate to the “wildrydes-site” folder that you copied on your machine.
  2. Open “/register.html”.
  3. After completing the registration form choose “Let’s Ryde”. Either use your own email or a fake one, it is up to you. The password you choose should have a number, special character and at least one upper-case letter. Make sure to remember this password.
  4. You can confirm the user by following one of the methods.
  5. If you have used your own email then you can verify your account by visiting “/verify.html” present under website domain and entering the verification code. It is must to check the spam folder because the verification mail might end up there.
  6. In case you have used a fake email, you will need to confirm the user manually using Cognito console.
  7. Select “WildRydes” user pool in the Amazon Cognito console.
  8. Go to the “Users” tab and choose the username to come across user detail page.
  9. In the dropdown menu of “Actions”, select the option “Confirm Account” to complete the creation process.
  10. Choose “Confirm” in the user pop-up as well.
  11. After confirming the user successfully, visit “/signin.html” page and use the email address and password you entered during the account creation step to perform a login.
  12. You will be redirected to “/ride.html” page in case of success.

Conclusion

In this guide, we have completed our work with just two modules i.e. hosting a static website and managing users. In depth details and steps have been demonstrated for your ease. Follow each and every step with proper understanding so the errors could be minimized. In the next guide, we will work on the remaining modules as well.