wesupport

Need help?

Our experts have had an average response time of 13.14 minutes in February 2024 to fix urgent issues.

We will keep your servers stable, secure, and fast at all times for one fixed price.

Build serverless web application with AWS lambda

by | Mar 1, 2021

Are you looking for steps to build a serverless web application with AWS lambda? We can help you build it.

Here at Bobcares, we have seen several such AWS-related queries as part of our AWS Support Services for AWS users, and online service providers.

Today we shall create a simple serverless web application that enables users to request unicorn rides from the Wild Rydes fleet.

 

Application Architecture to build serverless Web Application with AWS Lambda

The application architecture uses AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, and AWS Amplify Console.

This workshop comprises five modules. They are:

  1. Static Web Hosting
  2. User Management
  3. Serverless Backend
  4. RESTful APIs
  5. Resource Termination and Next Steps

 

Module 1. Static Web Hosting with Continuous Deployment

In this module, we shall configure AWS Amplify to host the static resources to the web application with continuous deployment built-in. All of the static web content including HTML, CSS, JavaScript, images, and other files is managed by AWS Amplify Console.

How to build serverless web application AWS lambda

Now let’s take a look at how our Support Engineers implement this.

 

Step 1: Select a Region

We can deploy the web application in any AWS region that supports all the services used in this application, which include AWS Amplify, AWS CodeCommit, Amazon Cognito, AWS Lambda, Amazon API Gateway, and Amazon DynamoDB.

We select the region from the dropdown in the upper right corner of the AWS Management Console.

 

Step 2: Create a Git repository

We can either manage the source code through AWS CodeCommit or GitHub. Here we are using CodeCommit to store our application code. Below are the steps that we follow:

  • First, we open the AWS CodeCommit console
  • Next, we select Create Repository
  • Here we set the Repository name* to “wildrydes-site”
  • Then we select Create
  • Now that we have created the repository, we set up an IAM user with Git credentials in the IAM console.
  • Then back in the CodeCommit console, From the Clone URL, drop down, we select Clone HTTPS
  • From a terminal window, we run git clone and the HTTPS URL of the repository:
    $ git clone https://git-codecommit.us-east1.bobcares.com/v1/repos/wildrydes-site Cloning into 'wildrydes-site'... Username for 'https://git-codecommit.us-east-1.bobcares.com':XXXXXXXXXX Password for 'USERID': XXXXXXXXXXXX warning: You appear to have cloned an empty repository.

 

Step 3: Populate the Git repository

Now we’ve created our git repository and cloned it locally. Now we need to copy the website content from an existing publicly accessible S3 bucket and add the content to your repository.

  • a. We change the directory into the repository and copy the static files from S3:
    cd wildrydes-site/
    aws s3 cp s3://wildrydes-us-east-1/WebApplication/1_StaticWebHosting/website ./ --recursive
  • b. Then we commit the files to the Git service
    $ git add .
    $ git commit -m 'new'
    $ git push

 

Step 4: Enable Web Hosting with the AWS Amplify Console

Now we shall use the AWS Amplify Console to deploy the website that we just committed to git. The Amplify Console takes care of the work of setting up a place to store the static web application code.

  • First, we launch the Amplify Console console page
  • Next, we click Get Started under Deploy with Amplify Console
  • Here we select the Repository service provider used today and select Next
  • Then from the dropdown, we select the Repository and Branch just created
  • On the “Configure build settings” page, we leave all the defaults and select Next.
  • On the “Review” page, we select Save and deploy
  • The process takes a couple of minutes for Amplify Console to create the necessary resources and to deploy the code.

After it completes, we click on the site image to launch the Wild Rydes site.

 

Step 5: Modify the site

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

  • a. First, we open the `index.html` page and modify the title line so that it says: <title>Wild Rydes – Rydes of Future!</title>
  • b. Then we save the file and commit to the git repository again. Once, the Amplify Console notices the update to the repository, it will begin to build the site again. It will happen pretty quickly. We then head back to the Amplify Console console page to watch the process.
    $ 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.bobcares.com/v1/repos/wildrydes-site
    2e9f540..dfec2e5 master -> master
  • c. Once completed, we re-open the Wild Rydes site and notice the title change.

 

Module 2. User Management

In this module, we shall create an Amazon Cognito user pool to manage the users’ accounts. Here we will deploy pages that enable customers to register as a new user, verify their email address, and sign into the site.

Here are the steps to implement it.

 

Step 1: Create an Amazon Cognito User Pool

There are two different mechanisms for authenticating users that Amazon Cognito provides. We can either use Cognito User Pools to add sign-up and sign-in functionality to the application. Or we can use Cognito Identity Pools to authenticate users through social identity providers such as Facebook, Twitter, or Amazon, with SAML identity solutions, or by using our own identity system.

Here we shall use a user pool as the backend for the provided registration and sign-in pages.

  • From the AWS Console, we click Services then select Cognito under Mobile Services.
  • Next, we choose to Manage your User Pools.
  • Then we choose to Create a User Pool
  • Here, we provide a name for the user pool such as WildRydes, then select Review Defaults
  • On the review page, we click Create pool.
  • We note the Pool Id on the Pool details page of your newly created user pool.

 

Step 2: Add an App to the User Pool

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

  • From the Pool Details page for the user pool, we select App clients from the left General Settings section in the navigation bar.
  • Next, we choose to Add an app client.
  • We give the app client a name such as WildRydesWebApp.
  • Then we uncheck the Generate client secret option. Client secrets aren’t currently supported for use with browser-based applications.
  • We choose to Create app client.
  • We note the App client id for the newly created application.

 

Step 3: Update the Website Config

The settings for the user pool ID, app client ID, and Region are present in /js/config.js file. We update this file with the settings from the user pool and app we created in the previous steps and upload the file back to the bucket.

  • From our local machine, we open `wild-ryde-site/js/config.js` in a text editor.
  • Then we update the cognito section with the correct values for the user pool and app we just created.
  • The updated config.js file should look as below. Note that the actual values for your file will be different:
    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',
    }
    };
  • We then save the modified file and push it to your Git repository to have it automatically deploy to Amplify Console.
    $ git push

 

Step 4: Validate your implementation

  • First, we visit /register.html under the website domain.
  • Now, we complete the registration form and choose Let’s Ryde. We enter an email. If you wish you can use a dummy email as well. Then we enter the password which we need to remember for later use. We see an alert that confirms that our user has been created.
  • We then confirm our new user using one of the two following methods.
    a. 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.
    b. If you used a dummy email address, you must confirm the user manually through the Cognito console.
  • From the AWS console, we click Services then select Cognito under Security, Identity & Compliance.
  • Then we choose Manage your User Pools
  • We select the WildRydes user pool and click Users and groups in the left navigation bar.
  • Here we see a user corresponding to the email address that we submitted through the registration page. We choose that username to view the user detail page.
  • Then we choose Confirm user to finalize the account creation process.
  • After confirming the new user using either the /verify.html page or the Cognito console, we visit /signin.html and log in using the email address and password we entered during the registration step.
  • If successful we should be redirected to /ride.html. We can see a notification that the API is not configured.

 

Module 3: Serverless Service Backend

In this module, we shall use AWS Lambda and Amazon DynamoDB to build a backend process for handling requests for the web application.

The browser application that we deployed in the first module allows users to request that a unicorn be sent to a location of their choice. In order to fulfill those requests, the JavaScript running in the browser will need to invoke a service running in the cloud.

Here are the steps to implement it:

Step 1: Create an Amazon DynamoDB Table

  • We make use of Amazon DynamoDB console to create a new DynamoDB table.
  • From the AWS Management Console, choose Services then select DynamoDB under Databases.
  • Choose Create table.
  • Enter Rides for the Table name. This field is case sensitive.
  • Enter RideId for the Partition key and select String for the key type. This field is case sensitive.
  • Check the Use default settings box and choose Create.
  • Scroll to the bottom of the Overview section of your new table and note the ARN. You will use this in the next section.

 

Step 2: Create an IAM Role for the Lambda function

  • From the AWS Management Console, we click on Services and then select IAM in the Security, Identity & Compliance section.
  • Next, we select Roles in the left navigation bar and then choose Create New Role.
  • Then we select Lambda for the role type from the AWS service group, then click Next: Permissions.
  • We begin typing AWSLambdaBasicExecutionRole in the Filter text box and check the box next to that role.
  • Then we choose Next Step.
  • We enter WildRydesLambda for the Role Name and choose Create Role.
  • Then we type WildRydesLambda into the filter box on the Roles page and choose the role we just created.
  • On the Permissions tab, we choose the Add inline policy link in the lower right corner to create a new inline policy.
  • Then we select Choose a service.
  • We begin typing DynamoDB into the search box labeled Find a service and select DynamoDB when it appears and choose Select actions.
  • We begin typing PutItem into the search box labeled Filter actions and check the box next to PutItem when it appears and select the Resources section.
  • With the Specific option selected, we choose the Add ARN link in the table section.
  • We then paste the ARN of the table you created in the previous section in the Specify ARN for table field, and choose Add.
  • After that, we choose Review Policy.
  • Finally, we enter DynamoDBWriteAccess for the policy name and choose Create policy.

 

Step 3: Create a Lambda Function for Handling Requests

AWS Lambda will run the code in response to events such as an HTTP request. In this step we’ll build the core function that will process API requests from the web application to dispatch a unicorn.

  • First, we choose Services then select Lambda in the Compute section.
  • Next, we click Create function.
  • We keep the default Author from scratch card selected.
  • Then we enter RequestUnicorn in the Name field.
  • Select Node.js 6.10 for the Runtime.
  • We ensure Choose an existing role is selected from the Role dropdown.
  • Select WildRydesLambda from the Existing Role dropdown and click on Create function.
  • After that, we scroll down to the Function code section and replace the exiting code in the index.js code editor with the contents of requestUnicorn.js.
  • Finally, we click “Save” in the upper right corner of the page.

 

Step 4: Validate the Implementation

  • From the main edit screen for the function, we select Configure test event from the the Select a test event… dropdown.
  • We keep Create new test event selected.
  • Then we enter TestRequestEvent in the Event name field
  • After that, we 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}}"
    }
  • Then we click Create.
  • On the main function, we edit screen click Test with TestRequestEvent selected in the dropdown.
  • We then scroll to the top of the page and expand the Details section of the Execution result section.
  • We 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": "*"
    }
    }

 

Module 4. RESTful APIs

In this module, we shall use Amazon API Gateway to expose the Lambda function we built in the previous module as a RESTful API. Now, let’s take a look at the implementation.

Step 1: Create a New REST API

  • First, in the AWS Management Console, we click Services then select API Gateway under Application Services.
  • Next, we choose Create API.
  • Then we select New API and enter WildRydes for the API Name.
  • We keep Edge optimized selected in the Endpoint Type dropdown.
  • Finally, we choose Create API

 

Step 2: Create a Cognito User Pools Authorizer

  • Under our newly created API, we choose Authorizers.
  • Then we choose Create New Authorizer.
  • After that, we enter WildRydes for the Authorizer name.
  • Then we select Cognito for the type.
  • In the Region drop-down under Cognito User Pool, we select the Region where we created our Cognito user pool in module 2 (by default the current region should be selected).
  • Here we enter WildRydes in the Cognito User Pool input.
  • Then we enter Authorization for the Token Source and choose Create.
  • We verify our authorizer configuration
  • Then we open a new browser tab and visit /ride.html under our website’s domain.
  • If we are redirected to the sign-in page, we sign in with the user we created in the last module. We will be redirected back to /ride.html.
  • We copy the auth token from the notification on the /ride.html,
  • Then we go back to the previous tab where we just finished creating the Authorizer
  • After that, we click Test at the bottom of the card for the authorizer.
  • Here we paste the auth token into the Authorization Token field in the popup dialog.
  • Finally, we click the Test button and verify that the response code is 200 and that we see the claims for our user displayed.

 

Step 3: Create a new resource and method

Now we shall create a new resource called /ride within our API.

  • In the left navigation, we click on Resources under our WildRydes API.
  • From the Actions dropdown, we select Create Resource.
  • Then we enter ride as the Resource Name.
  • We ensure the Resource Path is set to ride.
  • Then we select Enable API Gateway CORS for the resource and then we click Create Resource.
  • With the newly created /ride resource selected, from the Action dropdown, we select Create Method.
  • After that, we select POST from the new dropdown that appears, then we click the checkmark.
  • We then select Lambda Function for the integration type.
  • Next, we check the box for Use Lambda Proxy integration.
  • After that, we select the Region we are using for Lambda Region.
  • We enter the name of the function we created in the previous module, RequestUnicorn, for Lambda Function.
  • Then we choose Save.
  • When prompted to give Amazon API Gateway permission to invoke our function, we choose OK.
  • We choose on the Method Request card and choose the pencil icon next to Authorization.
  • Finally, we select the WildRydes Cognito user pool authorizer from the drop-down list and click the checkmark icon.

 

Step 4: Deploy Your API

From the Amazon API Gateway console, we choose Actions, Deploy API. We’ll be prompted to create a new stage. We use prod for the stage name.

  • In the Actions drop-down list, we select Deploy API.
  • Then we select [New Stage] in the Deployment stage drop-down list.
  • After that, we enter prod for the Stage Name and choose Deploy.
  • We note the Invoke URL. We will use it in the next section.

 

Step 5: Update the Website Config

Now we update the /js/config.js file in the website deployment to include the invoke URL of the stage we just created.

  • We open the config.js file in a text editor.
  • Next, we update the invokeUrl setting under the api key in the config.js file. We then set the value to the Invoke URL for the deployment stage we created in the previous section.
    An example of a complete config.js file is included below. However, the actual values in the file will be different.

    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: ‘https://rc7nyt4tql.execute-api.us-west-2.amazonaws.com/prod’ // e.g. https://rc7nyt4tql.execute-api.us-west-2.amazonaws.com/prod,
    }
    };
  • Finally, we save the modified file and push it to the Git repository to have it automatically deploy to Amplify Console.
    $ git push

 

Step 6: Validate your implementation

  • First, we visit /ride.html under your website domain.
  • If we are redirected to the sign in page, we sign in with the user we created in the previous module.
  • After the map has loaded, we click anywhere on the map to set a pickup location.
  • We choose Request Unicorn. We see a notification in the right sidebar that a unicorn is on its way and then we see a unicorn icon fly to our pickup location.

 

Module 5. Resource Cleanup

It is possible to terminate the AWS Amplify app, an Amazon Cognito User Pool, an AWS Lambda function, an IAM role, a DynamoDB table, a REST API, and a CloudWatch Log. It is a best practice to delete resources that we no longer use to avoid unwanted charges.

[Need any further assistance with AWS queries – We are here to help you.]

 

Conclusion

Today, we saw how our Support Engineers build serverless Web Application AWS Lambda.

Get 24x7 monitoring for your AWS servers

There are proven ways to get even more out of your AWS Infrastructure! Let us help you.

Spend your time in growing business and we will take care of AWS Infrastructure for you.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Categories

Tags