🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with node.js › define lambda function handler in node.js
Define Lambda function handler in Node.js - AWS Lambda
Set up your projectExample ... environment variablesUsing global stateBest practices · The Lambda function handler is the method in your function code that processes events....
🌐
GeeksforGeeks
geeksforgeeks.org › devops › aws-lambda-function-handler-in-nodejs
AWS Lambda Function Handler in Node.js - GeeksforGeeks
July 23, 2025 - Handler: index.handler · Runtime: nodejs14.x · CodeUri: . Description: A simple Lambda function · Now, run the command. sam local invoke MyLambdaFunction --event event.json · The handler is the entry point for your AWS Lambda function.
People also ask

How to deploy Node.js Lambda?
To deploy a Node.js Lambda function, write your code, zip the project directory (including node_modules), then upload it via the AWS Lambda console, CLI, or through AWS SAM/Serverless Framework. Set up the required handler and permissions.
🌐
hevodata.com
hevodata.com › home › learn › data strategy
NodeJS Lambda | The Complete Guide to Get Started 101
How to build Lambda layer for Node.js?
To build a Lambda layer for Node.js, package your Node.js dependencies into a nodejs directory, zip the directory, and upload it to AWS Lambda Layers via the AWS console or CLI. You can then attach the layer to your Lambda function to reuse dependencies across functions.
🌐
hevodata.com
hevodata.com › home › learn › data strategy
NodeJS Lambda | The Complete Guide to Get Started 101
Why use the Lambda function?
Lambda functions are useful because they allow you to run code without provisioning or managing servers, automatically scaling to handle varying loads, and only charging for the compute time used, making them cost-effective for event-driven applications.
🌐
hevodata.com
hevodata.com › home › learn › data strategy
NodeJS Lambda | The Complete Guide to Get Started 101
🌐
Hevo
hevodata.com › home › learn › data strategy
NodeJS Lambda | The Complete Guide to Get Started 101
January 12, 2026 - The NodeJS Lambda function handler is the event-processing mechanism in your function code. NodeJS Lambda executes the handler method when your function is called. The handler becomes available to handle another event when it departs or delivers ...
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with node.js
Building Lambda functions with Node.js - AWS Lambda
The console creates a Lambda function with a single source file named index.mjs. You can edit this file and add more files in the built-in code editor. In the DEPLOY section, choose Deploy to update your function's code. Then, to run your code, choose Create test event in the TEST EVENTS section. The index.mjs file exports a function named handler that takes an event object and a context object.
🌐
GitHub
github.com › janaz › lambda-request-handler
GitHub - janaz/lambda-request-handler: Package your Node.js web app as a Lambda function executed by an API Gateway or ALB event
Package your Node.js web app as a Lambda function executed by an API Gateway or ALB event - janaz/lambda-request-handler
Author   janaz
🌐
npm
npmjs.com › package › lambda-request-handler
lambda-request-handler - npm
March 31, 2025 - An npm module that allows your Node.js web applications to be deployed as an AWS Lambda function and invoked in response to API Gateway, HTTP API, or Application Load Balancer requests..
      » npm install lambda-request-handler
    
Published   Mar 31, 2025
Version   0.6.0
🌐
TutorialsPoint
tutorialspoint.com › home › aws_lambda › aws lambda function in node.js
AWS Lambda Function in NODEJS
August 12, 2019 - To writeAWS Lambda function in nodejs, we should first declare a handler first. The handler in nodejs is name of the file and the name of the export function.
Top answer
1 of 8
84

This is what I did:

index.js

exports.handler = async (event) => {
    console.log('hello world');

    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!')
    };

    return response;
};

package.json

// using require
"scripts": {
  "locally": "node -e \"console.log(require('./index').handler(require('./event.json')));\""
}

// or the following for ESM using import
"scripts": {
  "locally": "node --input-type=module -e \"import {handler} from './index.mjs'; console.log(await handler(JSON.parse(fs.readFileSync('./event.json'))));\""
}

event.json

{
  "Records": [
    {
      "eventVersion": "2.0",
      "eventSource": "aws:s3",
      "awsRegion": "eu-central-1",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "AIDAJDPLRKLG7UEXAMPLE"
      },
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "responseElements": {
        "x-amz-request-id": "C3D13FE58DE4C810",
        "x-amz-id-2": "FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "testConfigRule",
        "bucket": {
          "name": "my-bucket",
          "ownerIdentity": {
            "principalId": "A3NL1KOZZKExample"
          },
          "arn": "arn:aws:s3:::my-bucket"
        },
        "object": {
          "key": "HelloWorld.jpg",
          "size": 1024,
          "eTag": "d41d8cd98f00b204e9800998ecf8427e",
          "versionId": "096fKKXTRTtl3on89fVO.nfljtsv6qko"
        }
      }
    }
  ]
}

Shell

npm run locally

Output

> node -e "console.log(require('./index').handler({}));"

hello world
Promise { { statusCode: 200, body: '"Hello from Lambda!"' } }
2 of 8
52

You need to call your handler function from another file lets say testHandler.js in order to run via NodeJs.

This will be done like this

//import your handler file or main file of Lambda
let handler = require('./handler');

//Call your exports function with required params
//In AWS lambda these are event, content, and callback
//event and content are JSON object and callback is a function
//In my example i'm using empty JSON
handler.handlerEvent( {}, //event
    {}, //content
    function(data,ss) {  //callback function with two arguments 
        console.log(data);
    });

Now you can use node testHandler.js to test your handler function.

EDIT: Sample Event and content data as requested

Event:

{
    "resource": "/API/PATH",
    "path": "/API/PATH",
    "httpMethod": "POST",
    "headers": {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
        "cache-control": "no-cache",
        "CloudFront-Forwarded-Proto": "https",
        "CloudFront-Is-Desktop-Viewer": "true",
        "CloudFront-Is-Mobile-Viewer": "false",
        "CloudFront-Is-SmartTV-Viewer": "false",
        "CloudFront-Is-Tablet-Viewer": "false",
        "CloudFront-Viewer-Country": "IN",
        "content-type": "application/json",
        "Host": "url.us-east-1.amazonaws.com",
        "origin": "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
        "Via": "2.0 XXXXXXXXXXXXXX.cloudfront.net (CloudFront)",
        "X-Amz-Cf-Id": "XXXXXXXXXX51YYoOl75RKjAWEhCyna-fuQqEBjSL96TMkFX4H0xaZQ==",
        "X-Amzn-Trace-Id": "Root=1-XXX03c23-25XXXXXX948c8fba065caab5",
        "x-api-key": "SECUREKEY",
        "X-Forwarded-For": "XX.XX.XXX.XXX, XX.XXX.XX.XXX",
        "X-Forwarded-Port": "443",
        "X-Forwarded-Proto": "https"
    },
    "multiValueHeaders": {
        "Accept": [ "*/*" ],
        "Accept-Encoding": [ "gzip, deflate, br" ],
        "Accept-Language": [ "en-GB,en-US;q=0.9,en;q=0.8" ],
        "cache-control": [ "no-cache" ],
        "CloudFront-Forwarded-Proto": [ "https" ],
        "CloudFront-Is-Desktop-Viewer": [ "true" ],
        "CloudFront-Is-Mobile-Viewer": [ "false" ],
        "CloudFront-Is-SmartTV-Viewer": [ "false" ],
        "CloudFront-Is-Tablet-Viewer": [ "false" ],
        "CloudFront-Viewer-Country": [ "IN" ],
        "content-type": [ "application/json" ],
        "Host": [ "apiurl.us-east-1.amazonaws.com" ],
        "origin": [ "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop" ],
        "User-Agent": [ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" ],
        "Via": [ "2.0 XXXXXXXXXXXXXX.cloudfront.net (CloudFront)" ],
        "X-Amz-Cf-Id": [ "XXXXXXXXXhCyna-fuQqEBjSL96TMkFX4H0xaZQ==" ],
        "X-Amzn-Trace-Id": [ "Root=1-XXXXXXX67339948c8fba065caab5" ],
        "x-api-key": [ "SECUREAPIKEYPROVIDEDBYAWS" ],
        "X-Forwarded-For": [ "xx.xx.xx.xxx, xx.xxx.xx.xxx" ],
        "X-Forwarded-Port": [ "443" ],
        "X-Forwarded-Proto": [ "https" ]
    },
    "queryStringParameters": null,
    "multiValueQueryStringParameters": null,
    "pathParameters": null,
    "stageVariables": null,
    "requestContext": {
        "resourceId": "xxxxx",
        "resourcePath": "/api/endpoint",
        "httpMethod": "POST",
        "extendedRequestId": "xxXXxxXXw=",
        "requestTime": "29/Nov/2018:19:21:07 +0000",
        "path": "/env/api/endpoint",
        "accountId": "XXXXXX",
        "protocol": "HTTP/1.1",
        "stage": "env",
        "domainPrefix": "xxxxx",
        "requestTimeEpoch": 1543519267874,
        "requestId": "xxxxxxx-XXXX-xxxx-86a8-xxxxxa",
        "identity": {
            "cognitoIdentityPoolId": null,
            "cognitoIdentityId": null,
            "apiKey": "SECUREAPIKEYPROVIDEDBYAWS",
            "cognitoAuthenticationType": null,
            "userArn": null,
            "apiKeyId": "xxXXXXxxxxxx",
            "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
            "accountId": null,
            "caller": null,
            "sourceIp": "xx.xxx.xxx.xxx",
            "accessKey": null,
            "cognitoAuthenticationProvider": null,
            "user": null
        },
        "domainName": "url.us-east-1.amazonaws.com",
        "apiId": "xxxxx"
    },
    "body": "{\n    \"city\": \"Test 1 City\",\n    \"state\": \"NY\",\n    \"zipCode\": \"11549\"\n}",
    "isBase64Encoded": false
}

Content:

{
    "callbackWaitsForEmptyEventLoop": true,
    "logGroupName": "/aws/lambda/lambda-name",
    "logStreamName": "2018/11/29/[$LATEST]xxxxxxxxxxxb",
    "functionName": "lambda-name",
    "memoryLimitInMB": "1024",
    "functionVersion": "$LATEST",
    "invokeid": "xxxxx-xxx-11e8-xxx-xxxxxxxf9",
    "awsRequestId": "xxxxxx-xxxxx-11e8-xxxx-xxxxxxxxx",
    "invokedFunctionArn": "arn:aws:lambda:us-east-1:xxxxxxxx:function:lambda-name"
}
Find elsewhere
🌐
Dashbird
dashbird.io › home › tutorial: getting started with aws lambda and node.js
Tutorial: Getting Started with AWS Lambda and Node.js - Dashbird
August 3, 2023 - Paste the existing Lambda function from AWS into the file and edit it slightly. const moment = require('moment'); exports.handler = async (event) => { const min = 1; const max = 6; const randomNumber = Math.floor( Math.random() * (max - min + 1) ) + min; const now = moment().format(); const message = 'Your dice throw resulted in ' + randomNumber + ' and was issued at ' + now; return message; };
Top answer
1 of 5
25

AWS Lambda expects your module to export an object that contains a handler function. In your Lambda configuration you then declare the file that contains the module, and the name of the handler function.

The way modules are exported in Node.js is via the module.exports property. The return value of a require call is the contents of the module.exports property at the end of the file evaluation.

exports is just a local variable pointing to module.exports. You should avoid using exports, and instead use module.exports, since some other piece of code may overwrite module.exports, leading to unexpected behaviour.

In your first code example, the module correctly exports an object with a single function handler. In the second code example, however, your code exports a single function. Since this does not match AWS Lambda's API, this does not work.

Consider the following two files, export_object.js and export_function.js:

// export_object.js

function internal_foo () {
    return 1;
}

module.exports.foo = internal_foo;

and

// export_function.js

function internal_foo () {
    return 1;
}

module.exports = internal_foo;

When we run require('export_object.js') we get an object with a single function:

> const exp = require('./export_object.js')
undefined
> exp
{ foo: [Function: internal_foo] }

Compare that with the result we get when we run require('export_function.js'), where we just get a function:

> const exp = require('./export_funntion.js')
undefined
> exp
[Function: internal_foo]

When you configure AWS Lambda to run a function called handler, that is exported in a module defined in the file index.js, here is an approximation of Amazon does when a function is called:

const handler_module = require('index.js');
return handler_module.handler(event, context, callback);

The important part there is the call to the handler function defined in the module.

2 of 5
2

I have used like this.

//index.js

const user = require('./user').user;
const handler = function (event, context, callback) {
  user.login(username, password)
    .then((success) => {
      //success
    })
    .catch(() => {
      //error
    });
};

exports.handler = handler;



//user.js
const user = {
  login(username, password) {
   return new BPromise((resolve, reject) => {
     //do what you want.
   });
  }
};
export {user};
🌐
Claudia.js
claudiajs.com › tutorials › hello-world-lambda.html
Hello World AWS Lambda function
Now, create a simple JavaScript Lambda function – for example, in a file called lambda.js. For detailed information on the Lambda API, check out the Node.js Lambda Programming Model on AWS. exports.handler = function (event, context) { context.succeed('hello world'); };
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with node.js › using the lambda context object to retrieve node.js function information
Using the Lambda context object to retrieve Node.js function information - AWS Lambda
When Lambda runs your function, it passes a context object to the handler . This object provides methods and properties that provide information about the invocation, function, and execution environment.
🌐
DEV Community
dev.to › aws-builders › running-lambdas-locally-using-javascriptnodejs-21g
Running lambdas locally using Javascript/Node.js - DEV Community
December 29, 2024 - We will start by creating a demo application using init command and then further proceed to invoke lambda within the application code (Nodejs). 1> Navigate to the folder where you want to set up your project. ... This will create a basic Hello world application.It has a simple Lambda handler which it takes in the event and returns back the data received from a particular URL, along with a Hello World message.
🌐
Medium
medium.com › intrinsic-blog › basic-node-js-lambda-function-concepts-c0d1e00d4528
Basic Node.js Lambda Function Concepts | by Thomas Hunter II | intrinsic | Medium
May 29, 2018 - When working with Node.js applications the Handler Name has two parts. The first part is the name of the JavaScript file in the root of the Lambda Function (without an extension), then a period, then the name of the exported function.
🌐
Arpadt
arpadt.com › articles › types-of-lambda-handlers
The two types of Lambda handler functions
The third option is to return the promise itself, which is very useful when the lambda function needs to interact with another AWS services, like S3 or DynamoDB. In our case, if we don’t want to do anything else but multiplying the number by 2, we can write something like this: exports.handler = async (event) => { return multiplyByTwo(event.num) }
🌐
AWS re:Post
repost.aws › questions › QUKr6lOHtrTPCirOeeenR1BQ › trouble-specifying-handler-with-index-mjs-file-in-lambda-function-running-node-js-20
Trouble specifying handler with index.mjs file in Lambda function running Node.js 20 | AWS re:Post
April 9, 2024 - [+] Building Lambda functions with Node.js - Designating a function handler as an ES module - https://docs.aws.amazon.com/lambda/latest/dg/lambda-nodejs.html#designate-es-module · Additionally, with regards to My goal is to maintain both index.js and **index.mjs** files without renaming them, and easily switch between them if needed.
🌐
AWS
aws.amazon.com › blogs › compute › node-js-24-runtime-now-available-in-aws-lambda
Node.js 24 runtime now available in AWS Lambda | Amazon Web Services
November 25, 2025 - AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Resources: MyFunction: Type: AWS::Serverless::Function Properties: Handler: lambda_function.lambda_handler Runtime: nodejs24.x CodeUri: my_function/. Description: My Node.js Lambda Function
🌐
RisingStack
blog.risingstack.com › home › hírek, események › getting started with aws lambda & node.js
Getting Started with AWS Lambda & Node.js - RisingStack Engineering
May 29, 2024 - The Lambda function can complete in one of the following ways: timeout – the timeout specified by the user has been reached (defaults to 5 seconds as of now), controlled termination – the callback of handler function is called,
🌐
Hevo
hevodata.com › home › learn › data strategy
What is AWS Lambda Nodejs function?
January 11, 2026 - When Lambda executes the function, it calls this handler function. Lambda invocation events are passed to the handler by the AWS Lambda Nodejs function runtime.