Building Lambda functions with TypeScript in AWS CDK
Tags: cdk, typescript
Published: 2022-06-07 04:20:28


![Building Lambda functions with TypeScript](https://www.codewithyou.com/static/images/writing-typescript-lambda-in-aws-cdk.jpg)

Photo by [Zac Durant](https://unsplash.com/@zacdurant)

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](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html) construct, which uses [esbuild](https://esbuild.github.io/) to automatically transpile and bundle our code.

Let see how to do this.

## Infrastructure of the Lambda function

```typescript
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,
      },
    })
  }
}
```

Let's go over the code.

- The Lambda function uses the [NodejsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html) 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](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html#bundling) options: no minify, no sourcemap, all modules are bundled
- Other parameters are the same as the [NodejsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html) construct.

> **The code for this article is available on [GitHub](https://github.com/buithaibinh/cdk-lamnda-typecript)**

## Lambda function writing in TypeScript

```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',
    },
  }
}
```

This is simple Lambda function written in TypeScript.

## Deploying the Lambda function

Run the following command to deploy the Lambda function.

```bash
yarn deploy
```

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

![Lambda-result](https://www.codewithyou.com/static/images/posts/writing-typescript-lambda-in-aws-cdk_1.png)

## Cleaning up

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

```bash
npx cdk destroy
```

Thanks for reading! 🚀