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

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

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, it 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.

During this journey, basically, we will be using below set of commands-

#Step 1 - Download a sample application
sam init

#Step 2 - Navigate into project directory and Build your application
cd hello-world-app
sam build

#Step 3 - Deploy your application
sam deploy --guided

Prerequisite

  • An AWS Account
  • A Admin User With Access/Secret Key
  • Admin right on local system to install software
  • 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 office 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-

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

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

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 download. After that just install it by clicking next next.

Verify SAM CLI Installation

sam --version

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

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.

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

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

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

Step 8: Deploy Your Application to Cloud

We will 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.

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

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

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

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 output’s of stack are shown below. We will need HelloWorldApi value which is the API Gateway endpoint to test in further steps.

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

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

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

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 helloworld-cloudkatha in our case. You can simply delete the stack if you don’t want these resources anymore.

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

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.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

Suggested Read:

Leave a Reply

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