Build an AWS Serverless Web App with Amplify, Cognito, API-Gateway, CodeCommit, Lambda and DynamoDB

Vishvjeet_singh_rathore
13 min readJul 17, 2023

--

step-by-step guide to create a simple serverless web application that enables users to request unicorn rides from the Wild Rydes fleet.

AWS services used

AWS Lambda, AWS Amplify Console, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, AWS CodeCommit.

Overview

I created a simple serverless web application that enables users to request unicorn rides from the Wild Rydes fleet. The application will present users with an HTML-based user interface for indicating the location where they would like to be picked up and will interact with a RESTful web service on the backend 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.

Prerequisites

You will need an AWS account, an account with ArcGIS to add mapping to your app, a text editor, and a web browser.

Application architecture

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.

Architecture diagram
Architecture diagram

Step 1: Static Web Hosting with Continuous Deployment

To get started, you will configure AWS Amplify to host the static resources for your web application with continuous deployment built in

  • select a region
  • Create a Git repository
  1. Open the AWS CodeCommit console
  2. Select Create Repository
  3. Set the Repository name to “wildrydes-site”
  4. Select Create

5. Now that the repository is created, set up an IAM user with Git credentials in the IAM console following these instructions.

6. Back in the CodeCommit console, from the Clone URL dropdown, select Clone HTTPS

7. Open a terminal, command line, or Git shell. Run the git clone command with the HTTPS clone URL you copied to clone the repository.

$ git clone https://git-codecommit.us-east1.amazonaws.com/v1/repos/wildrydes-site
Cloning into ‘wildrydes-site’…
Username for ‘https://git-codecommit.us-east-1.amazonaws.com':XXXXXXXXXX
Password for ‘USERID’: XXXXXXXXXXXX
warning: You appear to have cloned an empty repository.

  • Populate the Git repository

Once you’ve used either AWS CodeCommit or GitHub.com to create your git repository and clone it locally, you’ll need to copy the website content from an existing publicly accessible S3 bucket associated with this workshop and add the content to your repository.

  • Change directory into your repository and copy the static files from S3:
cd wildrydes-site
aws s3 cp s3://wildrydes-us-east 1/WebApplication/1_StaticWebHosting/website ./ - recursive

Commit the files to your Git service

$ git add .
$ git commit -m 'new'
$ git push
successfull

You can see all the files are in the repo

  • Enable web hosting with the AWS amplify console

Next you’ll use the AWS Amplify Console to deploy the website you’ve just committed 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.

  1. Launch the Amplify Console console page
  2. Click Get Started under Deploy with Amplify Console

3. Select CodeCommit under Get started with Amplify Hosting

4. Select the Repository service provider used today and select Continue
5. If you used GitHub, you’ll need to authorize AWS Amplify to your GitHub account
6. From the dropdown, select the Repository and Branch you just created and select Next

7. On the Configure build settings page, leave all the defaults, Select Allow AWS Amplify to automatically deploy all files hosted in your project root directory and select Next.
8. On the “Review” page select Save and deploy

9. The process takes a couple of minutes for Amplify Console to create the necessary resources and to deploy your code.

deployed

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

Our first step Static Web Hosting with Continuous Deployment is completed

Step 2: User Management

I create an Amazon Cognito user pool to manage your users’ accounts

When users visit my website they will first register a new user account. For the purposes of this workshop we’ll only require them to provide an email address and password to register. However, you can configure Amazon Cognito to require additional attributes in your own applications.

After users submit their registration, Amazon Cognito will send a confirmation email with a verification code to the address they provided. To confirm their account, users will return to your site and enter their email address and the verification code they received. You can also confirm user accounts using the Amazon Cognito console with a fake email addresses for testing.

After users have a confirmed account (either using the email verification process or a manual confirmation through the console), they will be able to sign in. When users sign in, they enter their username (or email) and password. A JavaScript function then communicates with Amazon Cognito, authenticates using the Secure Remote Password protocol (SRP), and receives back a set of JSON Web Tokens (JWT). The JWTs contain claims about the identity of the user and will be used in the next module to authenticate against the RESTful API you build with Amazon API Gateway.

  • Create an amazon Cognito user pool and integrate an app to ypur user pool
  1. In the AWS Console, enter Cognito in the search bar and select Cognito from the search results.
  2. Choose Create user pool.

3. On the Configure sign-in experience page, in the Cognito user pool sign-in options section, select User name. Keep the defaults for the other settings, such as Provider types in the Authentication providers section. Choose Next.

4. On the Configure security requirements page, keep the Password policy mode as Cognito defaults. You can choose to configure multi-factor authentication (MFA) or choose No MFA and keep other configurations as default. Choose Next.

5. On the Configure sign-up experience page, keep everything as default. Choose Next.

6. On the Configure message delivery page, for Email provider, confirm that Send email with Amazon SES — Recommended is selected. In the FROM email address field, select an email address that you have verified with Amazon SES, following these instructions from the Amazon SES Developer Guide.

7. On the Integrate your app page, provide a name for your user pool such as WildRydes. Under Initial app client, give the app client a name such as WildRydesWebApp and keep other settings as default.

8. On the Review and create page, choose Create user pool.

  • Update the website config

The /js/config.js file contains settings for the user pool ID, app client ID and Region. Update this file with the settings from the user pool and app you created in the previous steps and upload the file back to your bucket

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

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

  • Validate your implementation

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

2. Complete the registration form and choose Let’s Ryde. 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.

verification successful

3. 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.

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

Step 3: Serverless Service Backend

I use use AWS Lambda and Amazon DynamoDB to build a backend process for handling requests for your web application. The browser application that you deployed in the first module allows users to request that a unicorn be sent to a location of their choice. To fulfill those requests, the JavaScript running in the browser will need to invoke a service running in the cloud.

  • Create an amazon DynamoDB Table
  1. From the AWS Management Console, choose Services then select DynamoDB under Databases.
  2. Choose Create table.

3. Enter Rides for the Table name. This field is case sensitive.
4. Enter RideId for the Partition key and select String for the key type. This field is case sensitive.

5. Check the Use default settings box and choose Create. Navigate to the Tables page in the DynamoDB console and wait for your table creation to complete. Once it is completed, select your table name.

6. Scroll to the bottom of the Overview section of your new table and choose Additional info. Note the ARN.

  • Create an IAM role for lambda function

Every Lambda function has an IAM role associated with it. This role defines what other AWS services the function is allowed to interact with. You’ll need to create an IAM role that grants your Lambda function permission to write logs to Amazon CloudWatch Logs and access to write items to your DynamoDB table.

  1. From the AWS Management Console, click on Services and then select IAM in the Security, Identity & Compliance section.
  2. Select Roles in the left navigation pane and then choose Create Role.

3. Underneath Trusted Entity Type, select AWS service. For Use case, select Lambda, then choose Next.

4. Typing AWSLambdaBasicExecutionRole in the Filter text box

5. Enter role name and Choose Create Role.

6. Type WildRydesLambda into the filter box on the Roles page and choose the role you just created.

7. On the Permissions tab, on the left under Add permissions, choose Create Inline Policy.

8. Select Choose a service.

9. Begin typing DynamoDB into the search box labeled Find a service and select DynamoDB when it appears..

10. Choose Select actions.

11. Begin typing PutItem into the search box labeled Filter actions and check the box next to PutItem when it appears.

12. Select the Resources section.

13. With the Specific option selected, choose the Add ARN link in the table section.

14. Paste the ARN of the table you created in the previous section in the Specify ARN for table field, and choose Add.

15. Choose Review Policy.

16. Enter DynamoDBWriteAccess for the policy name and choose Create policy.

Created
  • Create a lambda function for handling requests
  1. Choose Services then select Lambda in the Compute section.
  2. Click Create function.

3. Keep the default Author from scratch card selected.

4. Select Node.js 16.x for the Runtime

5. Ensure Use an existing role is selected from the Change default execution role dropdown.

6. Select WildRydesLambda from the Existing Role dropdown.

7. Click on Create function.

8. Scroll down to the Code source section and replace the existing code in the index.js code editor with the contents of requestUnicorn.js.

9. Choose Deploy.

  • Validate your implementation
  1. From the main edit screen for your function, select Test and choose Configure test event from the dropdown.
  2. Keep Create new event selected.
  3. Enter TestRequestEvent in the Event name field
  4. Copy and paste the following test event into the editor:
{
"path": "/ride",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Authorization": "eyJraWQiOiJLTzRVMWZs",
"content-type": "application/json; charset=UTF-8"
},
"queryStringParameters": null,
"pathParameters": null,
"requestContext": {
"authorizer": {
"claims": {
"cognito:username": "the_username"
}
}
},
"body": "{\"PickupLocation\":{\"Latitude\":47.6174755835663,\"Longitude\":-122.28837066650185}}"
}

5. Choose Save.
6. On the main function edit screen click Test with TestRequestEvent selected in the dropdown.
7. Scroll to the top of the page and expand the Details section of the Execution result section.
8. Verify that the execution succeeded and that the function result looks like the following

{
"statusCode": 201,
"body": "{\"RideId\":\"SvLnijIAtg6inAFUBRT+Fg==\",\"Unicorn\":{\"Name\":\"Rocinante\",\"Color\":\"Yellow\",\"Gender\":\"Female\"},\"Eta\":\"30 seconds\"}",
"headers": {
"Access-Control-Allow-Origin": "*"
}
}

Step 4: Deploy a RESTful API

I use Amazon API Gateway to expose the Lambda function i built in the previously as a RESTful API. This API will be accessible on the public Internet. It will be secured using the Amazon Cognito user pool you created in the previous module. Using this configuration, you will then turn your statically hosted website into a dynamic web application by adding client-side JavaScript that makes AJAX calls to the exposed APIs.

  • Create a new REST API
  1. In the AWS Management Console, click Services then select API Gateway under Application Services.
  2. Choose Create API. Underneath the Create new API section, make sure New API is selected.
  3. Select Build under REST API and enter WildRydes for the API Name.
  4. Choose Edge optimized in the Endpoint Type dropdown. Note: Edge optimized are best for public services being accessed from the Internet. Regional endpoints are typically used for APIs that are accessed primarily from within the same AWS Region.
  5. Choose Create API
  • Create new Resources and methods
  1. In the left nav, click on Resources under your WildRydes API.

2. From the Actions dropdown select Create Resource.

3. Enter ride as the Resource Name.

4. Ensure the Resource Path is set to ride.

5. Select Enable API Gateway CORS for the resource.

6. Click Create Resource.

7. With the newly created /ride resource selected, from the Action dropdown select Create Method.

8. Select POST from the new dropdown that appears, then click the checkmark.

9. Select Lambda Function for the integration type.

10. Check the box for Use Lambda Proxy integration.

11. Select the Region you are using for Lambda Region.

12. Enter the name of the function you created in the previous module, RequestUnicorn, for Lambda Function.

13. Choose Save.

create authorization

14. Choose on the Method Request card.

15. Choose the pencil icon next to Authorization.

16. Select the WildRydesAuthorizer Cognito user pool authorizer from the drop-down list, and click the checkmark icon.

  • Deploy your API
  1. In the Actions drop-down list select Deploy API
  2. Select [New Stage] in the Deployment stage drop-down list.
  3. Enter prod for the Stage Name.
  4. Choose Deploy.
  5. Note the Invoke URL.
  • Update the website config
  1. Open the config.js file in a text editor.
  2. Update the invokeUrl setting under the api key in the config.js file. Set the value to the Invoke URL

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

$ git add .
$ git commit -m "new_configuration"
$ git push

wrap up

Visit /signin.html under your website domain.

Visit /ride.html under your website domain.

If you are redirected to the ArcGIS sign-in page, sign in with the user credentials

After the map has loaded, click anywhere on the map to set a pickup location.

Choose Request Unicorn. You should see a notification in the right sidebar that a unicorn is on its way and then see a unicorn icon fly to your pickup location.

Thankyou

linkedin : https://www.linkedin.com/in/vishvjeet-s-r

--

--