AWS Builder Center

Building a Serverless Web Application Using AWS CDK and TypeScript

Learn how to define infrastructure as code using AWS CDK to deploy an API Gateway, AWS Lambda function, and DynamoDB table in TypeScript.

C++ Developer | Windows Internal
Introduction Serverless architectures allow developers to build and run applications without managing infrastructure. In this article, we will set up a fully serverless backend using AWS CDK to manage services seamlessly through code.
Prerequisites An active AWS Account and configured AWS CLI
Node.js (v18 or later) installed
AWS CDK CLI installed (npm install -g aws-cdk)
Step 1: Initialize the Project Initialize a new CDK project with TypeScript:
mkdir serverless-demo && cd serverless-demo
cdk init app --language typescript
Step 2: Define Infrastructure Update your lib/serverless-demo-stack.ts file to create a DynamoDB table, a Lambda function, and an API Gateway endpoint:
import * as cdk from 'aws-cdk-lib';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import { Construct } from 'constructs';
export class ServerlessDemoStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create DynamoDB Table
const table = new dynamodb.Table(this, 'ItemsTable', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
// Create Lambda Function
const handler = new lambda.Function(this, 'ItemHandler', {
runtime: lambda.Runtime.NODEJS_20_X,
code: lambda.Code.fromAsset('lambda'),
handler: 'index.handler',
environment: {
TABLE_NAME: table.tableName,
},
});
table.grantReadWriteData(handler);
// Create API Gateway
new apigateway.LambdaRestApi(this, 'Endpoint', {
handler: handler,
});
}
}
Step 3: Deploy the Stack Deploy your application to AWS:
cdk deploy
Clean Up To remove created resources and prevent unintended costs:
cdk destroy
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article