How to Build a Node.js Serverless Application using AWS SAM
Tags: aws, node, serverless, sam
Published: 2022-01-22 18:46:30

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](https://cloudkatha.com/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](https://cloudkatha.com/aws-lambda-with-java-a-step-by-step-tutorial/)**, 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](https://cloudkatha.com/what-is-aws-serverless-application-modelsam-everything-you-need-to-know/)**.

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](https://cloudkatha.com/how-to-build-a-node-js-serverless-application-using-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](https://nodejs.org/en/download/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qalikvtmbwqsa3yjqrh0.JPG)

**Verify Node Installation**

```
node -v 
```

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ecdp0s5f92mxzuqlwhom.JPG)

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

```
aws configure
```

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](https://cloudkatha.com/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](https://github.com/aws/aws-sam-cli/releases/latest/download/AWS_SAM_CLI_64_PY3.msi).


SAM CLI Installer : [Installer](https://github.com/aws/aws-sam-cli/releases/latest/download/AWS_SAM_CLI_64_PY3.msi)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tn7b6wrkf02p0af4nuk.JPG)


**Verify SAM CLI Installation**

```
sam --version
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ougqw8gehtbrwve1z9vf.JPG)

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](https://git-scm.com/download/win)

To install on Linux of Mac OS just [follow instructions here](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)

**Verify Git Installation**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qq9aqgcp7atyeqxvekw3.JPG)

## Step 5: Create a New Serverless Project

We will use command-

```
sam init
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2t2l817obnfxc7aps1n.JPG)

## 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
```
I am on windows. So I will use below command-

```

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

#listing files
dir
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lx53kvu10rwv8tdg9yts.JPG)
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

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

```
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
};
```

## 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
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgt5x1wxi7znozvbmilj.png)
 

## Step 8: Deploy Your Application to Cloud

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

```
sam deploy --guided
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3rq9nizx8c1tabg696el.png)
 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34txahrrye9reu0w9nqf.png)
 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfdqtsgxz078mg9extm2.png) 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy1df3kn7y3vw478w1a8.png)
 
**
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7m7ukl9dowvi9yj965c.png)
 



**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8kzjxhz6i1r8g1ckccr.png)

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

## 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](https://twitter.com/preetipragyacse) or Checkout [CloudKatha](https://cloudkatha.com) for more articles from me.