Mastering AWS Lambda: Deploying a Node.js Serverless Function with the Serverless Framework

Mastering AWS Lambda: Deploying a Node.js Serverless Function with the Serverless Framework

Introduction

Welcome to the world of AWS Lambda, a cornerstone of serverless computing. In this comprehensive guide, you’ll learn how to deploy a Node.js serverless function using AWS Lambda and the Serverless Framework. Whether you’re new to Lambda or want to deepen your practical knowledge, you’re in the right place.

Chapter 1: Understanding Serverless Computing

What is Serverless Computing?

Serverless computing is a cloud computing model that allows you to build and run applications without the need to manage the underlying infrastructure. In a serverless architecture, cloud providers like AWS take care of server provisioning, scaling, and maintenance, allowing you to focus solely on your application code.

EC2 vs. Serverless

Amazon EC2 (Elastic Compute Cloud)

  1. Requires manual provisioning and management of virtual machines (EC2 instances).

  2. Scaling is manual or requires complex auto-scaling configurations.

  3. You pay for reserved or on-demand instances, regardless of actual usage.

  4. Ideal for traditional applications requiring full control over the server environment.

Serverless (AWS Lambda)

  1. No need to manage servers; AWS Lambda handles infrastructure for you.

  2. Auto-scales automatically based on incoming traffic.

  3. Pay only for the compute time your functions consume.

  4. Perfect for event-driven, highly scalable, and cost-effective applications.

Advantages of Serverless Computing

  1. Cost-Efficiency: Pay only for what you use, with no upfront costs or idle resources.

  2. Auto-Scaling: Automatically handle traffic spikes without manual intervention.

  3. Managed Infrastructure: Focus on code, while cloud providers manage servers, networking, and security.

  4. Event-Driven: Easily integrate with various AWS services and trigger functions based on events.

  5. Global Reach: Deploy functions in multiple regions for low-latency access worldwide.

Disadvantages of Serverless Computing

  1. Vendor Lock-In: Code written for one provider may not be easily portable to another.

  2. Cold Starts: Initial invocation of a function can experience latency due to resource provisioning.

  3. Limited Execution Time: Functions are typically limited in runtime, which may not be suitable for long-running tasks.

Chapter 2: Prerequisites

Before we dive into deploying our serverless function, make sure you have the following prerequisites in place:

  • An AWS account: If you don’t have one, you can sign up for a free AWS account here.

  • Node.js and npm installed: You can download Node.js and npm from the official website here.

  • Serverless Framework installed: To install the Serverless Framework, run the following command in your terminal:
npm install -g serverless

Configuring AWS Access Keys

  1. If you haven’t already, you need to configure your AWS access keys. These keys consist of an Access Key ID and a Secret Access Key and are required for the Serverless Framework to interact with your AWS resources.

  2. To configure your AWS access keys, open your terminal and run the following command:

aws configure

3. You’ll be prompted to enter your AWS Access Key ID, Secret Access Key, default region, and default output format. You can obtain these keys from your AWS IAM (Identity and Access Management) dashboard.

  • Access your AWS IAM dashboard by logging in to your AWS account.

  • In the IAM dashboard, navigate to “Users” and select your user (or create a new one if necessary).

  • In the “Security credentials” tab, you can generate and retrieve your Access Key ID and Secret Access Key.

  • Enter these values when prompted by the aws configure command.|

Chapter 3: Creating a Serverless Service

  1. Open your terminal and create a new directory for your serverless project:
mkdir serverless-nodejs-app
cd serverless-nodejs-app
  1. Initialize a new Serverless service using the following command:
serverless create -t aws-nodejs -n serverless-nodejs-app

This command generates the necessary boilerplate code for a Node. js-based serverless service.

Chapter 4: Configuring the Serverless Framework

  1. Navigate to the newly created serverless-nodejs-app directory.

  2. Open the serverless.yml file and adjust the configuration to your preferences. You can specify the AWS region, stage, and other settings.

service: serverless-nodejs-app
provider:
  name: aws
  runtime: nodejs14.x
  stage: dev
  region: ap-south-1 # Change to your desired AWS region
functions:
  app:
    handler: handler.handler
    events:
      - http:
          path: /
          method: ANY

Chapter 5: Creating a GET Request Handler

  1. Inside your serverless-nodejs-app directory, you should have a file named handler.js. This is where you define your Lambda function handler.

  2. Open the handler.js file in your code editor and modify it to include a simple GET request handler that returns "Hello from blog.anilgulati.tech." Here's an example of what the handler.js file could look like:

// handler.js
module.exports.hello = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: 'Hello from blog.anilgulati.tech' }),
  };
};

In this code, we defined an async function called hello that takes an event as its parameter. This function returns a response with a 200 status code and the message "Hello from blog.anilgulati.tech."

  1. Save the changes to the handler.js file.

Chapter 6: Defining the Function in serverless.yml

Now, let’s update the serverless.yml file to specify this function:

service: serverless-nodejs-app
provider:
  name: aws
  runtime: nodejs14.x
  stage: dev
  region: ap-south-1 # Change to your desired AWS region
functions:
  app:
    handler: handler.hello # Update the handler to point to the hello function
    events:
      - http:
          path: /
          method: ANY

Make sure to update the handler field to point to the handler.hello function, as shown above.

Chapter 7: Deploying Your Serverless Function

  1. Deploy your serverless function by running the following command:
serverless deploy

This command packages your application, creates the necessary AWS resources, and deploys your function.

  1. After the deployment is complete, you’ll receive a URL where your serverless function is accessible. It will look something like this: https://your-api-id.execute-api.us-east-1.amazonaws.com/dev/.

Chapter 8: Testing Your Serverless Function

  1. Open a web browser or use a tool like curl to send a GET request to your function's URL. You should receive the "Hello from your serverless function!" response.

2. You can also test your function locally using the Serverless Framework. Run the following command to invoke your function locally:

serverless invoke local -f app

Chapter 9: Deploying to Production

To deploy your serverless function to a production environment, modify the serverless.yml file by changing the stage to production.

provider:
  name: aws
  runtime: nodejs14.x
  stage: production
  region: us-east-1 # Change to your desired AWS region

Then, redeploy your function using serverless deploy.

Conclusion: Congratulations! You’ve successfully deployed a Node.js serverless function using AWS Lambda and the Serverless Framework. This is just the beginning of your serverless journey. Explore more advanced features of AWS Lambda, optimize your serverless functions for performance and cost-efficiency, and continue building amazing serverless applications.

External Links: For further exploration, refer to the official AWS Lambda documentation and the Serverless Framework documentation.

Enjoyed This Article?

If you enjoy reading this post, got help, knowledge through it, and want to support my efforts please clap this article and follow.
To explore more of my work, visit my portfolio at
anilgulati.com