How to Use AWS Lambda with Node.js: Simple Guide
To use
AWS Lambda with Node.js, write a JavaScript function that exports a handler accepting event and context parameters. Deploy this function to Lambda, and AWS will run it in response to triggers like HTTP requests or events.Syntax
An AWS Lambda function in Node.js exports a handler function that AWS calls when the function runs. The handler receives two main inputs: event (data about the trigger) and context (runtime info). It returns a result or calls a callback to finish.
- exports.handler: The main function Lambda runs.
- event: Input data from the trigger.
- context: Info about the Lambda environment.
- callback: Function to send response or error.
javascript
exports.handler = async (event, context) => { // Your code here return 'Hello from Lambda!'; };
Example
This example shows a simple Lambda function in Node.js that returns a greeting message including a name passed in the event. It uses async/await and returns a JSON response.
javascript
exports.handler = async (event) => { const name = event.name || 'World'; const response = { statusCode: 200, body: JSON.stringify({ message: `Hello, ${name}!` }) }; return response; };
Output
{"statusCode":200,"body":"{\"message\":\"Hello, Alice!\"}"}
Common Pitfalls
Common mistakes when using Lambda with Node.js include:
- Not returning or calling the callback, causing the function to time out.
- Using synchronous code that blocks the event loop.
- Not handling errors properly, which can cause silent failures.
- Ignoring the
eventstructure and missing required input data.
Always use async functions or callbacks and handle errors with try/catch.
javascript
/* Wrong: Missing return or callback, causes timeout */ exports.handler = (event, context, callback) => { console.log('Hello'); // No return or callback }; /* Right: Using async and returning a response */ exports.handler = async (event) => { return 'Hello'; };
Quick Reference
| Concept | Description |
|---|---|
| exports.handler | Main function Lambda runs |
| event | Input data from trigger |
| context | Runtime info and methods |
| callback | Function to send response or error |
| async/await | Preferred for handling async code |
| Return value | Response sent back to caller |
Key Takeaways
Write your Lambda function as an exported handler accepting event and context.
Use async/await or callbacks to handle asynchronous code properly.
Always return a response or call the callback to avoid timeouts.
Handle errors with try/catch to prevent silent failures.
Test your function locally or in AWS Lambda console before deployment.