How to Use AWS Lambda with Node.js

This tutorial will show us how to use AWS Lambda And Node.js. This post will show how to configure the serverless on mac and up and running with aws lambda with nodejs from scratch. Finally, we will look at how we can deploy a simple test aws-nodejs application. But before we start, we need to understand some terminology. So let us know that first.

Function as a Service (FAAS)

AWS Lambda architecture is called either Serverless Computing or Function as a Service. It’s groundbreaking technology because of the lack of servers.

But wait, that sounds strange. Well, the code is not running on potatoes, is it!? Okay, that’s just a saying.

What’s going on here is that you, as a developer, don’t need to worry about the infrastructure your code is running on.

You deploy the code into the cloud, and it handles the creation of all needed resources using the containers.

Whenever an AWS Lambda Function is created, a container is spun up to serve it. It’s not a Docker container but a proprietary container built by AWS.

Principles of FaaS

  1. It completely abstracts the servers away from a developer.
  2. The billing is based on the consumption and executions of functions, not server instance sizes like Amazon EC2.
  3. Services that are event-driven and instantaneously scalable.

On a basic level, you can describe them as a way to run some code when ‘something happens or an event occurs, like receiving an HTTP request from the client.

Well-known FaaS Providers

AWS, Azure, and Google Cloud provide this serverless solution. Much innovation and R&D are still going on in this area, and things are rapidly improving and changing over time. Leading three in the industries is the following.

  1. AWS Lambda
  2. Azure Functions
  3. Cloud Functions

Serverless Framework

Serverless helps build web, mobile, and IoT applications using AWS Lambda and API Gateway, Azure Functions, Google Cloud Functions, and more.

Serverless computing is a cloud-computing execution model in which a cloud provider acts as a server, dynamically managing the allocation of machine resources. 

The pricing is entirely based on the number of resources an application consumes rather than on pre-purchased units of capacity used in traditional servers.

Serverless is the native architecture of a cloud that enables you to shift more of your operational responsibilities to AWS, increasing your ability towards your main application logic and less infrastructure-centric.

Serverless allows you to build and run applications and services without thinking about servers. 

It eliminates infrastructure management tasks such as server or cluster provisioning, patching, operating system maintenance, and capacity provisioning.

You can build on serverless for nearly any application or backend service, and everything required to run and scale your application with high availability is handled for you.

AWS Lambda And Node.js

For this task, you need to create an AWS account. It provides a Free-tier with limitations. You can create your free account here.

You will have node.js installed on your local machine. I am using MacBook Air, and my node version is 11.3.0.

It would be best if you also had an editor. I am using Visual Studio Code.

Step 1: Install Serverless Globally

The first step is to install serverless globally on your local machine. Type the following command to install. If you are using Windows, then open the CMD in administrator mode.

sudo npm install serverless -g

AWS Lambda And Node.js Tutorial | Getting Started With Serverless

Ignore that yellow warning; we have successfully installed the serverless on our machine.

The sudo command gives you complete root privileges, so you should use it properly.

Okay, now create a folder called node-lambda and go inside that folder and create an aws-nodejs template.

Now, we can use this serverless package to install a template specific to aws-nodejs. So, let us install an aws-nodejs template for serverless.

serverless create -t aws-nodejs

Aws Lambda Node.js Installation Template

Open the project on VSCode, and you will see the folder structure like this image.

AWS Node js Lambda Folder Structure

Step 2: Create Access Key and Secret For AWS

The next step is to create an access key and secret to connect the serverless with our aws account.

After your successful signup on AWS, you can create your access key and secret.

See the below image. When you log in, you can click on your name in the upper right corner, and you can see it opens up a drop-down and then click on the My Security Credentials.

You will see this kind of page with a popup.

Create Access Key and Secret For AWS

For this demo, let’s go with the Continue to Security Credentials. First, you can use the IAM Users policy to create and access specific users and policies.

Next, access keys (access key ID and secret access key) and create new keys. Finally, you can find both the access key and access secret.

Now, you need to provide those keys to the serverless to connect serverless and aws-nodejs.

For that, you need to type the following command in your terminal, and in between that command, you need to provide your access key and secret. You do not need to do it if you have already done it. Otherwise, it would be best if you did that.

serverless config credentials --provider aws --key your aws key --secret your aws secret

In the above command, you need to place your access key instead of your aws key and your access secret instead of your aws secret.

After hitting enter, if your credentials are correct, you will see a success message like the one below.

Setup AWS Serverless Setup

Bingo, you got it right, and now your configuration step is over.

Step 3: Creating your First Function

Now, open the editor in which your project is open and go to the handler.js file.

Modify that code with the following code.

// handler.js

'use strict';

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Expecto Petronum',
      input: event,
    }),
  };
};

So, when the HTTP request hits the AWS Lambda Service URL, we will get a response like this: Expecto Petronum.

Now, go to this file called serverless.yml.

I have modified that file with the following code and removed the commented part in the file.

service: lambda-test

provider:
  name: aws
  runtime: nodejs8.10

functions:
  hello:
    handler: handler.hello
    events:
     - http:
         path: users/create
         method: get

What I have done is first, I changed the service name to lambda-test and added a function called hello, which is inside the handler.js file.

So, when the request hits the URL, this function will execute and gives the response defined in that function.

Okay, now all the coding is done.

We need to deploy this function into AWS. So type the following command.

serverless deploy

Serverless deploy

If the deployment is the first time, you will see something like this.

Serverless AWS Lambda Deploy

So, the endpoint is generated for our service. We can use that endpoint as an API or web service to get a JSON response. So it also becomes a BaaS(Backend as a Service).

Here, in the console, I can see my endpoint to which I can get the response. You also have your endpoint, which you can access from your browser. So go to the browser and hit that endpoint, and you will see an output like this.

serverless aws nodejs tutorial

That is it, guys; we have successfully deployed our first function as a service using AWS Lambda.

Step 4: Create a second function

Go to the project inside the VSCode and open the serverless.yml file and add another function called app.

service: lambda-test

provider:
  name: aws
  runtime: nodejs8.10

functions:
  hello:
    handler: handler.hello
    events:
     - http:
         path: users/create
         method: get
  app:
    handler: handler.app
    events:
     - http:
         path: app/get
         method: get

Also, we need to write the code inside the handler.js file. 

This app function decides what to respond to when the URL hits the browser or the API endpoint gets accessed. But first, let us add a new position inside the handler.js file.

// handler.js

'use strict';

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Expecto Petronum',
      input: event,
    }),
  };
};

module.exports.app = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'AppDividend API is accessed',
      input: event,
    }),
  };
};

Save the file and deploy the code.

serverless deploy

Create a second function

See in the endpoints section: you now have two endpoints.

So, it is beneficial and easy to create a new function as a backend service, and you will be charged based on how many times your service has been accessed.

If you want to build an API and do not manage any server, then you have the best way to use AWS Lambda to avoid driving your server and focus on only the code. The rest will handle by the cloud service provider.

That’s it for this tutorial. Thanks for taking it.

3 thoughts on “How to Use AWS Lambda with Node.js”

  1. your teaching idea is awsome and your every toturial is unique.I like your toturial.But last some time i were thought upcoming Krunal sir toturail which one series start. Now realy you surprise everyone. Thanx for providing this series and please keep it up continue with full specification and fast to provide evry solution.Thanx

    Reply
  2. I followed all steps above but got:
    {
    “message”: “Internal server error”
    }
    // 20190315130646

    {
    “message”: “Internal server error”
    }

    Is there something I can use to debug?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.