Building a Serverless AWS Lambda Function in Node.js: A Step-by-Step Guide

Building a Serverless AWS Lambda Function in Node.js: A Step-by-Step Guide

Effortless Serverless: Creating and Deploying a Simple AWS Lambda Function using Node.js and SAM

ยท

4 min read

In this post, I'll guide you through the process of creating a serverless function using AWS Lambda and Node.js. I'll start with the basic "Hello World" function, then move on to deploying it using the Serverless Application Model (SAM).

Introduction โš

Serverless computing is a cloud computing execution model where the cloud provider dynamically manages the allocation of machine resources. Among the serverless services offered by AWS, Lambda is perhaps the most well-known, allowing you to run your code without provisioning or managing servers.

The Serverless Application Model (SAM) is an open-source framework for building serverless applications. It extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application.

Here is a video about this topic ๐Ÿš€

Prerequisites ๐Ÿ“ 

Before starting, you'll need the following:

  • An AWS account

  • AWS CLI installed and configured

  • AWS SAM CLI installed

  • Node.js installed (I'll use v14.x in this guide)

Step 1: Writing a Basic AWS Lambda Function in Node.js ๐Ÿ”

Let's start by writing a simple "Hello World" function in Node.js.

Create a new directory named hello-world in your AWS project directory. Inside this directory, create a file named app.js.

The content of app.js should be as follows:

exports.lambdaHandler = async (event, context) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello World from Lambda!'),
    };
    return response;
};

In this code, I've defined a basic asynchronous function lambdaHandler which returns a response object. The response object contains two fields: statusCode set to 200, indicating a successful HTTP request, and body, which contains a stringified version of 'Hello World from Lambda!'.

Step 2: Defining the AWS Resources with SAM โ˜๏ธ

Now that we have our function, I need to define the AWS resources I am going to use.

Create a new file named template.yaml in your aws directory. This file will contain the configuration for our AWS resources.

Here's the content of the template.yaml file:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Simple SAM Lambda Function

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs14.x
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /hello
            Method: get
Outputs:
  HelloWorldApi:
    Description: API Gateway endpoint URL for the Lambda function
    Value:
      Fn::Join:
        - ''
        - - 'https://'
          - Fn::Sub: '${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com'
          - '/Prod/hello/'

In this YAML file, I define a single resource, a HelloWorldFunction, of the type AWS::Serverless::Function. I set the properties for our Lambda function, such as the CodeUri which points to the code for our function, the Handler which specifies the file and exported function to execute, and the Runtime which specifies the runtime environment.

I also define an ApiEvent under Events to trigger our Lambda function. It's configured as a GET method at the /hello path.

The Outputs section helps us retrieve the API Gateway endpoint URL for our Lambda function.

Step 3: Building and Deploying the Function ๐Ÿšข

With our function written and resources defined, I am now ready to build and deploy our function. AWS SAM makes this process simple and straightforward.

In your terminal, navigate to the project directory and run the following command to build the application:

sam build

This command prepares your application for deployment by downloading the necessary dependencies and packaging your application code.

Once the build process completes, you can deploy your application using the sam deploy command. For a guided deployment process, you can use the --guided flag as shown below:

sam deploy --guided

This command will guide you through the initial deployment of your application. You'll be prompted to provide certain parameters like the stack name, AWS region, and whether you want to allow SAM to create IAM roles for your functions.

After entering the necessary information, SAM will create a CloudFormation Stack and begin deploying your resources.

Once the deployment process is complete, the Outputs section will provide you with the API Gateway endpoint URL for your Lambda function.

Step 4: Invoking the Function ๐Ÿ“ท

With our function successfully deployed, I can now invoke it by sending a GET request to the API Gateway endpoint URL.

You can do this using any HTTP client like curl, Postman, or even your web browser. Simply navigate to the provided URL, and you should see a response with 'Hello World from Lambda!'.

Wrapping Up ๐Ÿค—

And that's it! You've successfully created, built, and deployed a serverless AWS Lambda function using Node.js and AWS SAM.

Even though this is a straightforward example, the potential with AWS Lambda and SAM is vast. By combining different AWS services, you can build complex serverless applications that can scale automatically based on demand, all while keeping costs to a minimum.

This guide should serve as a starting point for your serverless journey. Feel free to modify and expand on this basic function as you explore what serverless computing on AWS has to offer.

You can Buy Me a Coffee if you want to and please don't forget to follow me on YouTube, Twitter, and LinkedIn also.

Happy coding!

ย