Open In App

How to Load NPM Modules in AWS Lambda?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

AWS Lambda is a serverless computing service within the event-driven model that Amazon Web Services provides; it is purposed for the execution of code without server provisioning or management. It automatically scales your application to handle from a few requests per day to thousands. This integrability with most AWS services and third-party APIs makes AWS Lambda one of the major benefits for modern, cloud-native applications.

Node.js is an open-source JavaScript runtime built on Chrome's V8 JavaScript engine, designed to build fast and scalable network applications. AWS Lambda supports Node.js, enabling the use of the huge ecosystem of Node.js modules available through the npm (Node Package Manager) for your Lambda functions.

Primary Terminologies

AWS Lambda

  • AWS Lambda is an event-driven serverless computing service of Amazon, provided as a part of the Amazon Web Services. It allows you to run code without provisioning or managing servers, scaling with the triggering of events automatically.

Node.js

  • Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code at the server end, it is based on Chrome's V8 JavaScript engine and follows the design principle of creating lightweight and scalable network applications.

npm (Node Package Manager)

  • npm is Node.js's default package manager. It provides a way to install, manage, and publish packages or modules of JavaScript code for use within a Node.js project. npm also offers a command-line interface with which to interact with repositories of Node.js packages.

Lambda Function

  • The unit of execution in AWS Lambda is a function; for example, in this case, the function represents a particular piece of code that executes a certain task when driven by events, examples of such events are HTTP requests, data manipulation in Amazon S3 buckets, and messages from AWS services like Amazon SNS and Amazon SQS.

Deployment Package

  • The deployment package is just a .zip file of your Lambda function code and any dependencies that you require for the execution. This package gets uploaded to AWS Lambda when you create or update your Lambda function.

Context Object

  • This is an object passed in as an argument into the Lambda handler and gives information about the invocation, runtime environment, and AWS resources linked with your Lambda function. This object includes function name, function version, function memory, function ARN, and more.

Lambda Layers

  • This is a key component of the AWS Lambda architecture, where it allows centrally shared code and data across multiple Lambda functions, you can package libraries, dependencies, and other files inside a layer and then reference that layer within your Lambda function.

Handler Function

  • The handler function is the entry point for your Lambda function code. The handler function is invoked in AWS Lambda with a pair of parameters: an event object and a context object.

Invocation:

  • An invocation is the act of calling or invoking a Lambda function in response to an event. There are two types of event invocations: synchronous and asynchronous.

Step-by-Step Process to load npm modules in AWS Lambda

Step 1: Add the NodeSource repository

  • Run the following command to set up the NodeSource repository for Node.js
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
Add the NodeSource repository

Step 2: Install Node.js

  • Now, install Node.js
sudo yum install -y nodejs
Install Node.js

Step 3: Verify the installation

  • Check if Node.js and npm are installed correctly
node -v
npm -v
Verify the installation

Step 4: Set Up Your Node.js Project

  • Initialize a new Node.js project using npm init and follow the prompts to create a package.json file.
mkdir my-lambda-function
cd my-lambda-function
npm init -y
Set Up Your Node.js Project

Step 5: Install the Required npm Modules

  • Use npm to install any modules you need. For example, to install the axios module
npm install axios
Install the Required npm Modules

Step 6: Write Your Lambda Function Code

  • Create a file named index.js and write your Lambda function code, making sure to import and use the installed npm modules.

const axios = require('axios');

exports.handler = async (event) => {

try {

const response = await axios.get('https://api.example.com/data');

return {

statusCode: 200,

body: JSON.stringify(response.data),

};

} catch (error) {

return {

statusCode: 500,

body: JSON.stringify({ error: 'Failed to fetch data' }),

};

}

};

Write Your Lambda Function Code

Step 7: Create the Deployment Package

  • Package your project into a .zip file to upload to AWS Lambda.
zip -r my-lambda-function.zip .
Create the Deployment Package
  • We can check the created zip file by using ll pr ls command
Screenshot-2024-07-13-151416

Step 8: Upload the Deployment Package to AWS Lambda

  • Navigate to the AWS Lambda console and create a new Lambda function.
Upload the Deployment Package to AWS Lambda
  • Choose "Upload from" and select "Upload a .zip file" as the code entry type.
Upload a .zip file
  • Upload your my-lambda-function.zip file.
my-lambda-function.zip
  • Here we see that zip file was uploaded
zip file

Step 9: Configure the Lambda Function

  • Set up your function's handler. For example, if your function code is in index.js and the handler function is handler, set the handler to index.handler.
  • Configure the function’s runtime to Node.js
 Configure the Lambda Function

Step 10: Test Your Lambda Function

  • Use the AWS Lambda console to create a test event and invoke your function to ensure it works correctly with the npm modules.
Test Your Lambda Function
Configuration Done

Conclusion

Summing up, the potential of mastering npm module integration with AWS Lambda through Node.js unlocks great power in serverless computing. That way, AWS Lambda sheds developers of overhead on server management and lets them focus on writing only efficient, event-driven code. With npm, developers have a huge library at their disposal, enabling them to easily improve functionality and fast-track development cycles. Throughout the document, we have covered basic concepts like Lambda functions, deployment packages, handler functions, and event-driven architecture. Practical steps in setting up a project, installing the required dependencies, and handling common issues, such as error management and local testing, are also included. Scalability is easier, and resource utilization is at its peak due to the pay-per-execution model of Lambda.

Best practices would be followed for a well-performing, secure, and cost-efficient application running in the cloud. Armed with these tools, developers can continue to innovate quickly, responding dynamically to user demands and creating resilient applications that will scale easily up and down as the workloads fluctuate. AWS Lambda, with Node.js and npm, combines the next step forward in modern cloud computing, making it possible for developers to deliver powerful, scalable solutions with unprecedented flexibility and efficiency.


Next Article
Article Tags :

Similar Reads