πŸš€ Getting started with AWS CDK + Typescript

Mithun Das
6 min readOct 2

What is CDK?

Cloud Development Kit aka CDK is an open-source software development framework that helps developers define cloud infrastructure in code aka Infrastructure as code (IaC) and provision it through AWS CloudFormation. It allows you to define AWS resources using familiar programming languages such as TypeScript, Python, Java, and more, instead of writing CloudFormation templates directly.

In 2019, AWS CDK reached general availability, with support for TypeScript and Python as the initial programming languages. As of 2023, CDK supports TS, JS, Python, Java, C# and Go.

In my opinion, being first class citizen Typescript is the most matured programming language when it comes to CDK followed by Python. TypeScript was the first language supported for developing AWS CDK applications, and for that reason, there is a substantial amount of example CDK code written in TypeScript.

Why do I need CDK?

Well, Infrastructure as Code (IaC) is a fundamental practice in modern cloud computing. It offers several benefits and addresses key challenges in managing infrastructure including

  • Automation
  • Reproducibility
  • Version Control
  • Collaboration

And many more. I will explain them in a separate article, today, let’s focus on CDK.

What will we build today?

We will build a simple REST API using following AWS resources

  • HTTP API Gateway
  • Lambda

I like to start with very basic and then in subsequent articles we will build on top of this.

Some key concepts

Before you start diving, it’s important to know some key concepts which you will come across quite often.

  • Constructs: Constructs are the basic building blocks of your AWS CDK application. They represent AWS resources or a sets of resources. There are 3 different types of Construct β€” L1, L2 & L3. More on this here.
  • Stacks: Stacks are a core concept in AWS CDK. Each AWS CDK app can contain multiple stacks, and each stack represents a set of AWS resources that are created and managed together. Stacks can depend on other stacks to create dependencies between resources.
  • Synthesizing and Deploying: Once you define your infrastructure using AWS CDK, you can use the CDK CLI to synthesize CloudFormation templates from your code. These templates can then be deployed to your AWS account using AWS CloudFormation.

Prerequisites

Before you begin, make sure you have the following prerequisites in place

  • AWS Account: No brainer :) You should have an AWS account with the necessary permissions to create and manage resources.
  • Node and npm: Ensure have Node.js and npm installed on your system. If can download and install from here.

AWS CLI: Install and configure the AWS Command Line Interface (CLI) by following the instructions here.

Install CDK

At this point you are ready to install CDK globally through npm.

npm install -g aws-cdk
npm install -g typescript
npm install -g esbuild

I usually prefer to use npx over npm which does not install the packages globally on your computer, maintaining a clean environment. You can read more about npm vs npx here.

If you decide to use npx then you ignore the first installation above.

Create the app

First off, open your terminal and create a folder where you want to create your app and issue below command and type β€œy” when prompted.

npx cdk@2 init app --language=typescript

β”œβ”€β”€ README.md
β”œβ”€β”€ bin
β”‚ └── cdk-lambda-apigateway.ts
β”œβ”€β”€ cdk.json
β”œβ”€β”€ jest.config.js
β”œβ”€β”€ lib
β”‚ └── cdk-lambda-apigateway-stack.ts
β”œβ”€β”€ node_modules

You will notice one typescript file under β€œbin” folder which represent your app and one under β€œlib” which represent the stack. In this article we will create one stack and all the resources will be created under this stack.

Define AWS resources

Open the cdk-lambda-apigateway-stack.ts in your favorite editor. I use VS code. To use apigateway v2, you need to install few more packages. Execute below script from the root folder. Note the version number 2.99.1. Ideally you want to use the same version you have in your package.json for aws-cdk-lib

npm install @aws-cdk/aws-apigatewayv2-alpha@2.99.1-alpha.0
npm install @aws-cdk/aws-apigatewayv2-integrations-alpha@2.99.1-alpha.0

Let’s start with creating the lambda function.

const getTodoLambda = new lambdanodejs.NodejsFunction(this, "getTodoLambda", {
runtime: lambda.Runtime.NODEJS_18_X,
timeout: cdk.Duration.seconds(5),
entry: "lambda/api-get-todo/index.js",
handler: "handler",
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
},
bundling: {
nodeModules: [],
externalModules: [],
},
layers: [],
});

lambda
└── api-get-todo
β”œβ”€β”€ index.js
└── package.json

const handler = async (event) => {
console.log(JSON.stringify(event, null, 2));

const data = [
{ id: 1, checked: false, todo: "Buy groceries for the week." },
{ id: 2, checked: false, todo: "Try a new recipe for dinner tonight." },
{ id: 3, checked: false, todo: "Clean the kitchen and do the dishes." },
];

let response = {
statusCode: 200,
body: JSON.stringify(data),
};
return response;
};

module.exports = { handler };

Now, integrate the lambda with HTTP Api resource

const httpApi = new apigwv2.HttpApi(this, "todo-http-api", {
description: "HTTP API For TODO application",
corsPreflight: {
allowHeaders: ["Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key"],
allowMethods: [
apigwv2.CorsHttpMethod.OPTIONS,
apigwv2.CorsHttpMethod.GET,
apigwv2.CorsHttpMethod.POST,
apigwv2.CorsHttpMethod.PUT,
apigwv2.CorsHttpMethod.PATCH,
apigwv2.CorsHttpMethod.DELETE,
],
allowCredentials: false,
allowOrigins: ["*"],
},
});

httpApi.addRoutes({
path: "/todo",
methods: [apigwv2.HttpMethod.GET],
integration: new HttpLambdaIntegration("getTodoLambdaIntegration", getTodoLambda),
});

new cdk.CfnOutput(this, `httpapidomain`, {
value: httpApi.apiEndpoint,
description: "HTTP API domain",
});

Now just add AWS account and region in the app. Note, you usually don’t hardcode account which will not work in CICD pipeline. I will explain that in another article where I will show you how to build pipeline using AWS CDK and Github Action.

#!/usr/bin/env node
import "source-map-support/register";
import * as cdk from "aws-cdk-lib";
import { CdkLambdaApigatewayStack } from "../lib/cdk-lambda-apigateway-stack";

const app = new cdk.App();
new CdkLambdaApigatewayStack(app, "CdkLambdaApigatewayStack", {
env: { account: "XXXX", region: "us-east-2" },
});

That’s it! Now you are ready to deploy your aws resources. But before you do that you need to do one last thing, called bootstrapping. You need to do it once for the environment.

Bootstrapping

Before you start deploying your resources you must bootstrap the environment for CDK. Bootstrapping is the process of provisioning resources for the AWS CDK before you can deploy AWS CDK apps into an AWS environment. An AWS environment is a combination of an AWS account and Region.

npx cdk@2 bootstrap aws://your_aws_account/us-east-2

You should see a stack β€” β€œCDKToolkit” created in your chosen region.

Deploy Your CDK Stack

Build your TypeScript code by running

npm run build

Deploy your CDK stack to AWS by running

npx cdk@2 deploy

Tip: if you don’t want to see the confirmation prompt every time, add below line inside your cdk.json

"requireApproval": "never",

At the end of your deployment you should see the the api domain. Copy that and test using curl

curl https://xxxx.execute-api.us-east-2.amazonaws.com/todo

Clean Up (Optional)

One of the biggest advantage of creating your stack using any IaC framework such as CDK is you can clean up/ destroy everything you created in just one command. To clean up your app run

npx cdk@2 destroy

🍎 Find the source code on my github

🌟 Coming up…

Consider subscribing and stay tuned for a series of upcoming articles dedicated to AWS CDK, where we’ll dive deeper into its features, share practical tips, and explore real-world use cases, helping you master the art of Infrastructure as Code.

  • Distributed map state function using CDK
  • Openserarch serverless using CDK
  • Lambda Edge With CDK
  • Lambda layers , authorizers and dynamodb
  • Github Action With CDK

If you are interested in other topics, let me know in the comment section.

Mithun Das

Sr Principal Engineer | Tech Enthusiast | AWS Certified Solutions Architect | IoT Evangelist