DEV Community

Cover image for Building Reusable Infrastructure with AWS CDK (TypeScript
Ravi Kant Shukla
Ravi Kant Shukla

Posted on

Building Reusable Infrastructure with AWS CDK (TypeScript

Leverage the power of AWS CDK v2 and TypeScript to write modular, scalable, and production-ready infrastructure code. This article guides you through CDK structuring best practices for reusability.

Why Use AWS CDK?
CDK enables developers to define cloud infrastructure using programming languages. It outputs CloudFormation templates but gives you the flexibility of loops, conditionals, and modularization.

Start Simple: One Stack for All
When learning CDK, it's common to define all resources in a single Stack.

// app-stack.ts
...
new s3.Bucket(this, 'MyBucket');
new lambda.Function(this, 'MyLambda', ...);
new apigateway.LambdaRestApi(this, 'MyAPI', { handler: myLambda });

Enter fullscreen mode Exit fullscreen mode

Great for demos, but bad for real-world projects.

Split and Reuse: Create L3 Constructs
Refactor your resources into purpose-driven constructs.

// lib/s3-construct.ts
...
export class S3Construct extends Construct {
  public readonly bucket: s3.Bucket;
  ...
}
Enter fullscreen mode Exit fullscreen mode

Use these constructs inside stacks to organize your code.

Parameterize with Context
Avoid hardcoded values by passing inputs via cdk.json.

{
  "context": {
    "env": "dev",
    "lambdaTimeout": 10
  }
}
const env = this.node.tryGetContext('env');

Enter fullscreen mode Exit fullscreen mode

Compose Constructs Together
Wire up reusable constructs in a meaningful sequence.

const producer = new LambdaToSqs(this, 'Producer');
new SqsToDynamo(this, 'Consumer', { queue: producer.queue });
Keeps each piece independently testable and reusable.

Share Your Constructs via Package
Extract constructs to a private npm package or shared GitHub repo:

import { MyApiConstruct } from '@your-org/cdk-constructs';
Enter fullscreen mode Exit fullscreen mode

Quick Setup Guide

Step 1: Initialize Project

mkdir cdk-reuse-example && cd cdk-reuse-example
cdk init app --language=typescript
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Packages

npm install aws-cdk-lib constructs
npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda @aws-cdk/aws-apigateway @aws-cdk/aws-sqs
Enter fullscreen mode Exit fullscreen mode

Step 3: Create L3 Constructs

Add modular components to lib/ directory.

Step 4: Use Context

Add cdk.json configuration and access using node.tryGetContext().

Step 5: Compose in Stack

Use your custom constructs inside the stack to connect resources.

Step 6: Deploy

cdk synth
cdk diff
cdk deploy
Enter fullscreen mode Exit fullscreen mode

Final Thoughts
Clean infra-as-code = faster delivery
Modular structure = better testability
Context = dynamic environments
Reusable constructs = shared ownership

Top comments (0)