DEV Community

Binh Bui
Binh Bui

Posted on

Building Lambda functions with TypeScript in AWS CDK

Building Lambda functions with TypeScript

Photo by Zac Durant

You can use the Node.js runtime to run TypeScript code in AWS Lambda. Because Node.js doesn't run TypeScript code natively, you must first transpile your TypeScript code into JavaScript. Then, use the JavaScript files to deploy your function code to Lambda. Your code runs in an environment that includes the AWS SDK for JavaScript.

In order to write a Lambda function in TypeScript and provision it with CDK, we have to use the NodejsFunction construct, which uses esbuild to automatically transpile and bundle our code.

Let see how to do this.

Infrastructure of the Lambda function

export class CdkStarterStackStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props)
    // lambda function

    const testFn = new NodejsFunction(this, 'MyFunction', {
      entry: './lambda/index.ts',
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'main',
      bundling: {
        externalModules: ['aws-sdk'],
        minify: false,
Enter fullscreen mode Exit fullscreen mode

Let's go over the code.

  • The Lambda function uses the NodejsFunction construct, which automatically transpiles and bundles our code, regardless if it's written in JavaScript or TypeScript

  • entry Path to the entry file (JavaScript or TypeScript).

  • bundling options: no minify, no sourcemap, all modules are bundled

  • Other parameters are the same as the NodejsFunction construct.

The code for this article is available on GitHub

Lambda function writing in TypeScript

import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda'

export async function main(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
  // this response will be returned to the API Gateway
  // it support both rest api and http api
  return {
    body: JSON.stringify({ message: 'Hello from Lambda!' }),
    statusCode: 200,
    isBase64Encoded: false,
    headers: {
      'Content-Type': 'application/json',
Enter fullscreen mode Exit fullscreen mode

This is simple Lambda function written in TypeScript.

Deploying the Lambda function

Run the following command to deploy the Lambda function.

yarn deploy
Enter fullscreen mode Exit fullscreen mode

Now the Lambda function is deployed to AWS Lambda. You can test it by lambda console.


Cleaning up

Don't forget to delete the Lambda function when you're done.

npx cdk destroy
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! 🚀

Top comments (0)