- 1 year ago
How to debug AWS Lambda Node.js locally using serverless module?
To debug AWS Lambda functions written in Node.js locally using the Serverless framework, you can follow these steps:
Install Dependencies: Ensure you have Node.js, npm, and the Serverless CLI installed on your local machine.
Create a Serverless Project: Set up a new Serverless project or use an existing one. If you don't have a project yet, you can create one using the following command:
cssserverless create --template aws-nodejs --name my-lambda-project
cd my-lambda-project
Install the AWS SDK: Install the AWS SDK in your project directory to simulate the Lambda environment locally.
npm install aws-sdk
Install
serverless-offline
Plugin: Install theserverless-offline
plugin, which allows you to run your Lambda functions locally.cssnpm install serverless-offline --save-dev
Configure
serverless.yml
: In yourserverless.yml
file, add theserverless-offline
plugin and set thelambdaPort
andhttpPort
to run your Lambda functions locally.yamlservice: my-lambda-project
provider:
name: aws
runtime: nodejs14.x
plugins:
- serverless-offline
custom:
serverless-offline:
httpPort: 3000
lambdaPort: 5000
Add a Debugger to Your Code: To enable debugging, add the following line at the beginning of your Lambda function code:
javascriptif (process.env.IS_LOCAL) {
require('source-map-support').install();
}
Start Local Environment: Start the local environment using the
serverless offline
command:sqlserverless offline start
This will start a local server that mimics the AWS Lambda environment.
Debug with Visual Studio Code: To debug your Lambda functions, you can use Visual Studio Code (VSCode) with the
serverless-offline
plugin. Open your project in VSCode, set breakpoints in your Lambda function code, and then use the "Run and Debug" feature to start the local server with debugging enabled.In the
.vscode/launch.json
file, create a new configuration for debugging the Lambda functions:json{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Lambda",
"type": "node",
"request": "attach",
"port": 9229,
"localRoot": "${workspaceFolder}/",
"remoteRoot": "/var/task",
"skipFiles": ["<node_internals>/**"]
}
]
}
Start Debugging: With the configuration set up, click the "Run and Debug" button in VSCode, select the "Attach to Lambda" configuration, and click the green play button to start debugging your Lambda function locally.
Now, you can send HTTP requests to your local Lambda functions, and the debugger in VSCode will catch any breakpoints you've set in your code.
Please note that the serverless-offline
plugin and VSCode debugging setup enable you to simulate the Lambda environment locally, but there might still be some differences compared to the real AWS Lambda environment. Always thoroughly test your Lambda functions on the AWS platform before deploying them to production.