How to debug Lambda functions with Visual Studio Code
In this example we will look at how to debug AWS Lambda functions with Visual Studio Code (VS Code) using SST.
SST allows you to build and test Lambda functions locally using Live Lambda Development. This means that you can attach breakpoints and inspect your Lambda functions locally, even if they are invoked remotely.
Here is a video of it in action.
Let’s look at how.
Requirements
- Node.js 16 or later
- We’ll be using TypeScript in this example but you can use regular JavaScript as well
- An AWS account with the AWS CLI configured locally
Create an SST app
Let’s start by creating an SST app.
$ npx create-sst@latest --template=base/example vscode
$ cd vscode
$ npm install
By default, our app will be deployed to the us-east-1
AWS region. This can be changed in the sst.config.ts
in your project root.
import { SSTConfig } from "sst";
export default {
config(_input) {
return {
name: "vscode",
region: "us-east-1",
};
},
} satisfies SSTConfig;
Project layout
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
packages/functions/
— App CodeThe code that’s run when your API is invoked is placed in the
packages/functions/
directory of your project.
Setting up our API
For this example we’ll be testing using a simple API endpoint.
Replace your stacks/ExampleStack.ts
with the following.
import { Api, StackContext } from "sst/constructs";
export function ExampleStack({ stack }: StackContext) {
// Create the HTTP API
const api = new Api(stack, "Api", {
routes: {
"GET /": "packages/functions/src/lambda.handler",
},
});
// Show the API endpoint in the output
stack.addOutputs({
ApiEndpoint: api.url,
});
}
Adding function code
Our functions are stored in the packages/functions/
directory. In this case, we’ll have a simple Lambda function that’s printing out the time the request was made.
Create a packages/functions/src/lambda.ts
with.
import { APIGatewayProxyEventV2, APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = async (
event: APIGatewayProxyEventV2
) => {
const message = `The time in Lambda is ${event.requestContext.time}.`;
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, World! ${message}`,
};
};
Adding VS Code Launch Configurations
To allow VS Code to set breakpoints and debug our Lambda functions we’ll add it to our Launch Configurations. The starter template should already come with this but you can also add it manually by doing the following.
Create a .vscode/launch.json
file with.
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug SST Dev",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/sst",
"runtimeArgs": ["start", "--increase-timeout"],
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"]
}
]
}
Extending Lambda function timeouts
Since we are going to set breakpoints in our Lambda functions, it makes sense to increase the timeouts.
SST has an --increase-timeout
option that increases the function timeouts in your app to the maximum 15 minutes. We are using this option in our launch.json
.
"runtimeArgs": ["start", "--increase-timeout"],
Note that, this doesn’t increase the timeout of an API. Since those cannot be increased for more than 30 seconds. But you can continue debugging the Lambda function, even after the API request times out.
Starting your dev environment
Now if you open up your project in VS Code, you can set a breakpoint in your packages/functions/src/lambda.ts
.
Next, head over to the Run And Debug tab > select the above configured Debug SST Dev, and hit Play.
The first time you start the Live Lambda Development environment, it’ll take a couple of minutes to do the following:
- It’ll bootstrap your AWS environment to use CDK.
- Deploy a debug stack to power the Live Lambda Development environment.
- Deploy your app, but replace the functions in the
packages/functions/
directory with ones that connect to your local client. - Start up a local client.
Once complete, you should see something like this.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-vscode-ExampleStack: deploying...
✅ dev-vscode-ExampleStack
Stack dev-vscode-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://siyp617yh1.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created. Now if you head over to that endpoint in your browser, you’ll notice that you’ll hit the breakpoint.
Making changes
An advantage of using the Live Lambda Development environment is that you can make changes without having to redeploy them.
Replace packages/functions/src/lambda.ts
with the following.
import { APIGatewayProxyEventV2, APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = async (
event: APIGatewayProxyEventV2
) => {
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, World! Your request was received at ${event.requestContext.time}.`,
};
};
Now if you head back to the endpoint.
https://siyp617yh1.execute-api.us-east-1.amazonaws.com/
You should see the new message being printed out.
Deploying your API
Now that our API is tested and ready to go. Let’s go ahead and deploy it for our users.
However, we are going to deploy your API again. But to a different environment, called prod
. This allows us to separate our environments, so when we are working in our local stage, it doesn’t break the API for our users.
Run the following in your terminal.
$ npx sst deploy --stage prod
A note on these environments. SST is simply deploying the same app twice using two different stage
names. It prefixes the resources with the stage names to ensure that they don’t thrash.
Cleaning up
Finally, you can remove the resources created in this example using the following command.
$ npx sst remove
And to remove the prod environment.
$ npx sst remove --stage prod
Conclusion
And that’s it! You’ve got a brand new serverless API. A local development environment, to test and make changes. And you can use Visual Studio Code to debug and set breakpoints in your Lambda functions. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/serverless-stack/sst/tree/master/examples/vscodeFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
WebSocket API
Building a simple WebSocket API.
-
Go REST API
Building a REST API with Golang.
-
Custom Domains
Using a custom domain in an API.
Web Apps
-
React.js
Full-stack React app with a serverless API.
-
Next.js
Full-stack Next.js app with DynamoDB.
-
Vue.js
Full-stack Vue.js app with a serverless API.
-
Svelte
Full-stack Svelte app with a serverless API.
-
Gatsby
Full-stack Gatsby app with a serverless API.
-
Angular
Full-stack Angular app with a serverless API.
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
CRUD DynamoDB
Building a CRUD API with DynamoDB.
-
PlanetScale
Using PlanetScale in a serverless API.
Authentication
Using SST Auth
-
Facebook Auth
Adding Facebook auth to a full-stack serverless app.
-
Google Auth
Adding Google auth to a full-stack serverless app.
Using Cognito Identity Pools
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Facebook Auth
Authenticating a serverless API with Facebook.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using Cognito User Pools
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
-
Google Auth
Authenticating a full-stack serverless app with Google.
-
GitHub Auth
Authenticating a full-stack serverless app with GitHub.
-
Facebook Auth
Authenticating a full-stack serverless app with Facebook.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
-
Kinesis data streams
A simple Kinesis Data Stream system.
-
EventBus
A simple EventBridge system with EventBus.
Editors
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
Miscellaneous
-
Lambda Layers
Using the chrome-aws-lambda layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.