AppDividend
Latest Code Tutorials

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

0 261

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see AWS Lambda And Node.js Tutorial | Getting Started With Serverless. In this post, we will see how we can configure the serverless on mac and up and running with aws lambda with nodejs from scratch. We will look at how we can deploy a simple test aws-nodejs application. But before the start, we need to understand some terminology. So let us know that first.

Function As A Service (FAAS)

The architecture AWS Lambda is called either a 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 by itself using the containers.

Every time an AWS Lambda Function is created, a container is spun up to serve it. It’s not a Docker container though, instead of 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 event occurs like receive an HTTP request from the client.

Well known FaaS Providers

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

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

Serverless Framework

Serverless is useful to 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 actual amount of resources consumed by an application, 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 type of 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 Tutorial

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

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

You also need to have an editor. I am using Visual Studio Code.

Step 1: Install Serverless Globally

The first step is to install serverless globally in your local machine. Type the following command to install. If you are using Windows, then open the CMD on 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 in our machine.

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

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 logged in, you can click on your name on 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. However, you can go with the IAM Users policy to create and give access to specific users and policies.

Next, go for Access keys (access key ID and secret access key) and create new keys. You can find both access key and access secret.

Now, you need to provide that 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. If you have already done it, then you do not need to do that. Otherwise, you need to do 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 place your access secret instead of your aws secret.

After hitting the enter, if your credentials are right, then you will see a success message like 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 hit the AWS Lambda Service URL, we will get a response like this message which is 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 have changed the service name to lambda-test and added a function called hello, which is inside the handler.js file.

So, when the request hit 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 the AWS. So type the following command.

serverless deploy

 

Serverless deploy

If the deployment is the first time, then 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 give the response when the URL hit in the browser or API endpoint gets accessed. Let us add a new function 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 have now 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 this best way to use AWS Lambda to avoid managing your server and focus on only the code. Rest will handle by the cloud service provider.

Finally, AWS Lambda And Node.js Tutorial | Getting Started With Serverless post is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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