How to create a Node.js Lambda and deploy it using AWS SAM?

How to create a Node.js Lambda and deploy it using AWS SAM?

In one of the previous blog posts, we have talked about creating an AWS Lambda function using Node.js and deploying it using the console. We used a template function provided by AWS and use the console to configure it. We have also talked about What is AWS SAM and tried to understand the template of AWS SAM.

In this blog post, we will create a boilerplate function that can be deployed to AWS Lambda using AWS SAM. If you are not aware of any of the stuff, you can click on the links highlighted in the post to get more information.

Code Structure

The following image shows the code structure of a repository which I will be using to explain the various parts of the function.

This image is taken from the barebone template I have in the GitHub repository. You can access the repository here.

The above directory structure has two folders.

  • src: used to structure all the source code files
  • test: used to structure all the test case files which should write to unit test our function code.

The rest of the files in the repo are for helping us to make development easier. The template file will be used to deploy the function using AWS SAM. The following image shows the template file.

We have discussed this template in the blog post Understanding AWS SAM templates.

There is an Index file in the src directory that will act as our entry point for the lambda function. The code mentioned in the Index file is

async function handleEvent(event) {
  // write code here
  console.log("Hello Lambda!!!", event); // eslint-disable-line no-console
}

module.exports = {handleEvent};

To deploy this function, go to the directory of the function and open a terminal. Once the terminal opens up, type in the following command:

sam deploy --guided

This will open up an interactive terminal that will guide you through the deployment process.

The boilerplate is available as a template repository on GitHub and is available here. You can use it to create an AWS Lambda function and deploy it using AWS SAM.

In the next blog post, we will extend our quest further and will create an API gateway that can call an AWS Lambda function. This will all be deployed using AWS SAM. Till then Happy Coding.

Subscribe to AWSMAG

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe