DEV Community

Preeti Pragya
Preeti Pragya

Posted on • Originally published at cloudkatha.com

How to Build a Node.js Serverless Application using AWS SAM

Dear reader, I hope you are doing great. Few days ago, I wrote a post on “How to Run “Hello World” on AWS Lambda in 5 Minutes”.

If you are a beginner to AWS Lambda, I would request you to go through that post before proceeding with this one. Because, that post is gonna give you a good taste of lambda and what you can do with it.

Having said that, although that post gives a great insight into getting started with AWS lambda, but is far from perfect in terms of what you would expect in real life.

In real life, you won’t be creating a lambda function in console. The best way to create and manage lambda function is by using SAM or Serverless Application Model.

And that’s why, I am here with this tutorial.

What we are gonna do today?

We are going to setup local development environment on a windows 10 system. And, we will do that using SAM or Serverless Application Model. For your information, SAM is nothing but an open source framework for building serverless applications.

More on that here: All You Need to Know About AWS SAM

Once environment is setup, we will create a Node.js lambda function. We will expose this lambda function to internet using an API Gateway endpoint. Once deployed to AWS cloud, we will test the endpoint and complete this tutorial.

Prerequisite

  1. An AWS Account
  2. An Admin User With Access/Secret Key
  3. Admin rights on local system to install software
  4. Basic Knowledge of SAM and Node.js

Steps to Build a Node.js Serverless Application using AWS SAM

  1. Install Node.js Runtime
  2. Install and Configure AWS CLI
  3. Install SAM CLI
  4. Install Git
  5. Create a New Serverless Project
  6. Understanding the Created Project
  7. Build the Application
  8. Deploy Your Serverless Application to Cloud
  9. Verify the Serverless Application
  10. Clean Up

Step 1: Install Node.js Runtime

In this tutorial, we are going to create Node.js lambda, so we will need node runtime to be installed on the system.

Go to official page of node.js and click on the MSI installer as per your system.

Once you click on the installer, go next-next and finish the installation. Below are the things that gets installed as part of it-

Image description

Verify Node Installation

node -v 
Enter fullscreen mode Exit fullscreen mode

Step 2: Install and Configure AWS CLI

AWS SAM is gonna use AWS CLI credentials to send API requests to AWS. So you should install AWS CLI on your system and configure it using access key/secret key of your user which has all the permission for this tutorial. It’s good to go ahead with an admin user.

To check if you already have AWS CLI setup, you can use below command-

aws configure list
Enter fullscreen mode Exit fullscreen mode

Image description

As you can see in above screenshot, for me it’s showing none. Therefore, I will setup my CLI using below command-

aws configure
Enter fullscreen mode Exit fullscreen mode

one you hit enter, it will ask you details like access key, secret key, region etc. Provide these information one by one and you are done.

In case you need help in setting up CLI, I have a tutorial for you : How to Install and Configure AWS CLI on Windows

Step 3: Install SAM CLI

We will use AWS SAM CLI to create, build and deploy a serverless application to AWS. Before that, lets install AWS SAM CLI

I am installing SAM CLI on windows and its super simple. All I need to do is Click on this MSI installer.

SAM CLI Installer : Installer

As soon as you click on this, installer is downloaded. After that just install it by clicking next next.

Image description

Verify SAM CLI Installation

sam --version
Enter fullscreen mode Exit fullscreen mode

Image description

SAM CLI is installed successfully.

Step 4 : Install Git

In the next step, we will be creating a SAM project using sam init. For this command to work, you must have git installed on your system.

And, the reason is it downloads a sample project from github if you don’t have git installed, it is going to fail.

Install git from here : Install Git on Windows

To install on Linux of Mac OS just follow instructions here

Verify Git Installation

Image description

Step 5: Create a New Serverless Project

We will use command-

sam init
Enter fullscreen mode Exit fullscreen mode

Navigate to folder in which you would like to create your application and then fire sam init command

You will be prompted for a series of questions . Provide your answers like below-

Which template source would you like to use? : AWS Quick Start Templates
Choose an AWS Quick Start application template: Hello World Example
Use the most popular runtime and package type? (Nodejs and zip) [y/N]: y
Project name [sam-app]: demo-node-app
Below is a screenshot for you in case you need any help.

Image description

Step 6: Understanding the Created Project

Project is created and if you want to check what all is created, just cd into the project directory and fire a command to list files.

# Navigate into the project directory
cd demo-node-app 

#listing files on linux or mac
ls -a

#listing files on windows
dir
Enter fullscreen mode Exit fullscreen mode

I am on windows. So I will use below command-


# Navigate into the project directory
cd demo-node-app 

#listing files
dir
Enter fullscreen mode Exit fullscreen mode

Image description
There are two important files that we need to understand

  1. template.yml
  2. app.js # Inside hello-world folder

Let’s take a look at each one of them and try to understand.

template.yml

This template.yml contains all the resource that we are gonna create on AWS. In our case, it case a lambda function and an API Gateway.

It also contains few outputs like API Gateway endpoint URL, function ARN and role ARN. After the deployment these will get printed in the CLI and you can use them for further process like testing the API Gateway endpoint.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  demo-node-app

  Sample SAM Template for demo-node-app

Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs14.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
            Path: /hello
            Method: get

Outputs:
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

Enter fullscreen mode Exit fullscreen mode

In case you are thinking that, hey I don’t see any API Gateway resource here.

Well, it’s part of lambda and is represented by below section

      Events:
        HelloWorld:
          Type: Api 
            Path: /hello
            Method: get

Enter fullscreen mode Exit fullscreen mode

It means it is going to create a single get endpoint represented by /hello.

app.js

You will find app.js inside hello-world folder.

app.js contains the actual lambda handler that will be called when someone calls this lambda.

For example, when API Gateway is going to call HelloWorld lambda, this lambdaHandler method will be called and a response of “hello world” is gonna be returned as specified in the below code of course along side the statusCode.

API Gateway kind of expects response in this format and if you try to deviate from it you might end up in 502 errors from API gateway.

let response;

exports.lambdaHandler = async (event, context) => {
    try {
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};
Enter fullscreen mode Exit fullscreen mode

Step 7: Build the Application

Our project is created, so lets build them to create a deployment package.

We are already inside project directory, so lets fire build command like below-

sam build
Enter fullscreen mode Exit fullscreen mode

Image description

Step 8: Deploy Your Application to Cloud

We'll use below command to deploy it to AWS Cloud

sam deploy --guided
Enter fullscreen mode Exit fullscreen mode

You will again be prompted with a lot of questions. Answer them per below screenshot. In case you don’t want to provide value for a particular question, just hit enter and it will take it’s default value.

Image description

Image description

After that it shows the change set that it is deploying. Verify the change set and enter y to go ahead with the deployment.

Image description

It takes some time to create resources. After a while I got the message that :

Successfully created/updated stack – hello-world-cloudkatha in eu-west-1

All the outputs of stack are shown below. We'll need HelloWorldApi value which is the API Gateway endpoint to test in further steps.

Image description

**
API Gateway Endpoint:** https://dqybwb0a7f.execute-api.eu-west-1.amazonaws.com/Prod/hello/

Step 9: Verify the Serverless Application

We already have the endpoint URL from previous step. Lets hit the endpoint URL in browser and you will see-

Image description

Congratulations !!!

You have successfully created , build and deployed a Node.js serverless application into AWS.

Step 10: Clean Up

If you check in AWS CloudFormation console, you will see that SAM creates your application stack which is hello–world-cloudkatha in our case. You can simply delete the stack if you don’t want these resources anymore.

Image description

First stack is what we created for our lambda function. Second one is SAM default stack that has been created by SAM and it contains two resources.

You only need to create stack for your resources as second one is part of SAM setup and will be needed when you created other projects.

In case you will want to delete the stack from CLI use below command:

aws cloudformation delete-stack --stack-name hello-world-cloudkatha --region eu-west-1
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In this post, we learnt to Build a Node.js Serverless Application using AWS SAM. We did setup our local environment with SAM and then we created, build and deployed the application on AWS Cloud.

After deploying, we tested the generated API Gateway endpoint URL to see if everything worked as expected. If you have any doubt, please feel free to drop a question in comment section.

Reach out to me on Twitter or Checkout CloudKatha for more articles from me.

Top comments (0)