AWS Lambda Function Handler in Node.js
Last Updated :
01 Aug, 2024
AWS Lambda is a powerful, effective service offered by Amazon Web Services that enables code to be run in a serverless style. Essentially, this means you don't have to manage underlying infrastructure, worry about scaling, patching, and managing servers; all of this gets done automatically by Lambda so that you can focus solely on writing code that responds to events.
The function handler in AWS Lambda is the method in your code that AWS Lambda uses to execute a function while a request is made. It's essentially an entry point for your Lambda function and holds the major processing logic for incoming events, it holds the main logic to be executed, processing the incoming data to perform any necessary operations, and then finally returning some form of response.
We will learn how to create, write, and test a handler for an AWS Lambda function in Node.js, and finally we will deploy it. And so we should go through this article because what you will learn here is how to properly set up your Lambda function so that it works as expected and is very well integrated with most of the AWS services. Whether you are just beginning with serverless computing or looking into building better serverless applications, knowing the Lambda function handler is key.
Primary Terminologies
- AWS Lambda: An AWS serverless computing service which allows running code in response to events without managing servers. With AWS Lambda, you only need to write your code because most of the heavy lifting related to infrastructure, scaling, and maintenance is done by AWS Lambda.
- Function Handler: The entry point for your AWS Lambda function. That is, the main function that AWS Lambda executes when it invokes an event for a function that is configured to process such an event. The handler processes the event data and returns a response. In Node.js, this is a JavaScript function defined in your code.
- Event: An object that contains data about the event source, which in turn has triggered the Lambda function, like HTTP request details, messages from a queue, or changes in the S3 bucket. The structure of the event object depends on the event source.
- Context: An object that provides run-time information to the Lambda function execution. It carries invocation metadata such as the function name, version, and memory allocation of the context. The context object also contains methods to interact with the Lambda execution environment.
- Lambda Expression: The part in AWS Lambda that contains your code and the settings you can configure. A Lambda function is defined by the code you write and the settings you have, which include memory size, timeout, and IAM permissions.
- IAM Role - Identity and Access Management Role: Permissions applied to your Lambda function, defining a set of actions it can carry out and on what resources. IAM roles ensure that your Lambda function has all the necessary permissions for access to other AWS resources.
- Serverless Computing: A cloud computing model wherein the allocation of machine resources is managed dynamically by the cloud provider, in this model developers write software to be executed in response to events without needing to explicitly manage infrastructure resources.
- Deployment Package: A ZIP file/ Container Image containing your Lambda function code along with all the dependencies Examples: Code file for a Node.js function should be: a javascript file with actual code - node_modules, along with other project files.
Step-by-Step Process AWS Lambda function handler in Node.js
Step 1: Set Up AWS CLI and Lambda Execution Role
pip install awscli
Configure AWS CLI
aws configure
Step 2: Create an IAM Role
- Go to the AWS IAM console and create a role with the "AWSLambdaBasicExecutionRole" policy
Step 3: Write the Lambda Function Handler
Example Lambda Function (index.js):
exports.handler = async (event, context) => {
// Log event and context
console.log("Received event:", JSON.stringify(event, null, 2));
console.log("Execution context:", JSON.stringify(context, null, 2));
// Simple response
return {
statusCode: 200,
body: JSON.stringify({
message: "Hello from Lambda!",
input: event,
}),
};
};
Step 4: Package and Deploy the Lambda Function
Create a Deployment Package:
Zip the index.js file:
Deploy the Lambda Function
- Use the AWS CLI to create or update the Lambda function:
aws lambda create-function --function-name myLambdaFunction \
--runtime nodejs14.x \
--role arn:aws:iam::account-id:role/role-name \
--handler index.handler \
--zip-file fileb://function.zip
Step 5: Test the Lambda Function
- Test in AWS Console: Go to the AWS Lambda console, select your function, and use the "Test" feature to provide sample event data and execute the function.
Test Locally with AWS SAM CLI
pip3 install aws-sam-cli
- Create an event.json file to simulate an event:
{
"key1": "value1",
"key2": "value2"
}
Create template.yml for Context
Here is the template.yml file
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs14.x
CodeUri: .
Description: A simple Lambda function
Step 6: Run the sam local invoke Command
sam local invoke MyLambdaFunction --event event.json
Handler in Node.js
The handler is the entry point for your AWS Lambda function. In simple terms, it's the function that will be invoked when the AWS Lambda service calls a function you've written. Your Lambda function defines a handler both in the code of your function and in function configuration. In the previous example, the handler function is an entry point. That is what AWS Lambda executes when the Lambda function is called.
Example Handler in Node.js:
exports.handler = async (event) => {
// Your logic here
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
};
- In the example above, the handler function is the entry point. When the Lambda function is invoked, AWS Lambda executes this function.
Params to Handler
The handler function in Node.js accepts two main parameters: event and context.
- Event: It is the parameter that encapsulates all the event data that caused the function to be executed. For an AWS Lambda, if it was executed due to an HTTP request through API Gateway, this parameter would encapsulate details of the HTTP request.
Example event parameter:
{
"resource": "/{proxy+}",
"path": "/examplepath",
"httpMethod": "GET",
"headers": {
"Accept": "application/json"
},
"queryStringParameters": {
"param1": "value1"
},
"body": null,
"isBase64Encoded": false
}
- Context: This parameter contains information about the invocation, function, and execution environment. It includes methods and properties to give details regarding the remaining execution time of the function, AWS request ID, log group, and stream.
Example context parameter:
exports.handler = async (event, context) => {
console.log('Function name:', context.functionName);
console.log('Remaining time (ms):', context.getRemainingTimeInMillis());
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
};
Error Handling in Node.js
Error Handling in Node.js In a way, error handling in AWS Lambda functions written in Node.js can be handled in standard JavaScript/Node.js error-handling techniques. You must gracefully handle errors to make your function behave predictably and provide useful information on errors.
Using try...catch for Synchronous Code:
exports.handler = async (event) => {
try {
// Your logic here
throw new Error('Something went wrong');
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: JSON.stringify('Internal Server Error'),
};
}
};
Using try...catch for Asynchronous Code:
exports.handler = async (event) => {
try {
const result = await someAsyncFunction();
return {
statusCode: 200,
body: JSON.stringify(result),
};
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: JSON.stringify('Internal Server Error'),
};
}
};
Handling Errors with Callbacks
- If you're using the callback pattern, handle errors by passing them to the callback function.
exports.handler = (event, context, callback) => {
someAsyncFunction((error, result) => {
if (error) {
console.error(error);
callback(null, {
statusCode: 500,
body: JSON.stringify('Internal Server Error'),
});
} else {
callback(null, {
statusCode: 200,
body: JSON.stringify(result),
});
}
});
};
Custom Error Handling
- You can define custom error classes to handle specific error types more gracefully.
class CustomError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
exports.handler = async (event) => {
try {
// Your logic here
throw new CustomError('Custom Error Message', 400);
} catch (error) {
console.error(error);
return {
statusCode: error.statusCode || 500,
body: JSON.stringify(error.message || 'Internal Server Error'),
};
}
};
Conclusion
A Lambda function handler in Node.js is the most important concept one needs to understand while developing robust and scalable serverless applications. It's basically a function that is at the core of your Lambda function—the one that defines how events are processed and responses constructed. If you understand the main terminologies, including event objects, context, and the handler function signature, you will be able to write and manage your Lambda function successfully.
You can use AWS Lambda to build applications that respond to events or requests and automatically scale your application. By putting the AWS SDK at your disposal, it allows your Lambda functions to access a wide variety of AWS services—helping you build very powerful cloud applications from within.
Such best practices as optimizing your deployment package and understanding IAM roles for safe permissions make your Lambda functions efficient and secure, leveraging the various tools and features that AWS has in store would enable you to build robust serverless applications to meet the need of modern cloud solutions.
With this knowledge, you are well-set to create, deploy, and manage AWS Lambda functions with writing Node.js code, thereby enjoying the power of serverless computation to build inventive and intelligent application solutions.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read