@codedrifters/constructs
v0.0.41
Published
Constructs frequently used in CodeDrifter projects.
Readme
@codedrifters/constructs
A collection of reusable AWS CDK constructs frequently used in CodeDrifters projects. This package provides pre-configured, secure, and production-ready constructs for common AWS infrastructure patterns.
Table of Contents
- What are AWS CDK Constructs?
- Installation
- Constructs
- Complete Example
- API Reference
- Further Documentation
What are AWS CDK Constructs?
AWS CDK (Cloud Development Kit) constructs are reusable cloud components that encapsulate AWS resources and their configuration. Think of them as building blocks that combine multiple AWS services into higher-level abstractions.
For example, instead of manually configuring an S3 bucket, CloudFront distribution, Route53 records, and SSL certificates separately, a construct can combine all of these into a single "StaticHosting" construct that you can use with just a few lines of code.
Key Benefits:
- Reusability: Write once, use everywhere
- Consistency: Enforce best practices and security defaults
- Simplicity: Complex infrastructure becomes simple API calls
- Type Safety: Full TypeScript support with IntelliSense
For more information about AWS CDK constructs, see the AWS CDK Developer Guide.
Installation
Add the package to your CDK project using Configulator/Projen configuration. This ensures consistent dependency management across your project.
Note: Always configure dependencies through Projen configuration files, never by manually running
npm install,pnpm add, oryarn add. Manual installation will create conflicts with Projen-managed files.
In a Monorepo (Recommended)
If you're using @codedrifters/configulator in a monorepo, add the package as a dependency in your sub-project configuration:
import { TypeScriptProject } from '@codedrifters/configulator';
import { MonorepoProject } from '@codedrifters/configulator';
const myCdkProject = new TypeScriptProject({
name: 'my-cdk-project',
packageName: '@myorg/my-cdk-project',
outdir: 'packages/my-cdk-project',
parent: root, // Your MonorepoProject instance
deps: [
'@codedrifters/constructs',
],
devDeps: [
'aws-cdk-lib@catalog:', // Catalog versions are pre-configured
'constructs@catalog:',
],
});In a Standalone CDK Project
If you're using AWS CDK directly (not via Configulator), add the package to your deps array:
import { awscdk } from 'projen';
const project = new awscdk.AwsCdkTypeScriptApp({
name: 'my-cdk-app',
deps: [
'@codedrifters/constructs',
],
devDeps: [
'aws-cdk-lib',
'constructs',
],
});After Adding to Configuration
After updating your projenrc configuration file, run:
npx projenThis will update your package.json and install the dependencies.
Peer Dependencies
This package requires the following peer dependencies:
aws-cdk-lib- AWS CDK construct libraryconstructs- Core constructs library
These should be added as dev dependencies in your project configuration. If you're using @codedrifters/configulator, the catalog versions (@catalog:) are automatically configured in the root MonorepoProject.
Constructs
S3 Constructs
PrivateBucket
A secure S3 bucket with sensible security defaults. This construct extends AWS CDK's Bucket construct with security best practices applied by default.
Security Defaults:
- Public access is blocked (
BlockPublicAccess.BLOCK_ALL) - SSL/TLS is enforced for all requests
- Bucket owner enforced object ownership
- Configurable removal policy (defaults to
RETAIN)
Basic Usage:
import { PrivateBucket } from '@codedrifters/constructs';
import { Stack } from 'aws-cdk-lib';
import { Construct } from 'constructs';
const stack = new Stack(app, 'MyStack');
// Create a private bucket with default security settings
const bucket = new PrivateBucket(stack, 'MyPrivateBucket');With Custom Properties:
import { RemovalPolicy } from 'aws-cdk-lib';
import { PrivateBucket } from '@codedrifters/constructs';
const bucket = new PrivateBucket(stack, 'MyPrivateBucket', {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
versioned: true,
});Note: The security settings (public access blocked, SSL enforced, etc.) cannot be overridden - they are always applied to ensure bucket security.
Static Hosting Constructs
StaticHosting
A complete static website hosting solution that creates and configures:
- S3 Bucket: Private bucket for storing static files (using
PrivateBucket) - CloudFront Distribution: Global CDN for fast content delivery
- SSL Certificate: Wildcard certificate via AWS Certificate Manager
- Route53 Records: DNS entries for the domain and wildcard subdomains
- Lambda@Edge Function: Viewer request handler for path rewriting
- SSM Parameters: Stores bucket ARN, distribution domain, and distribution ID for later use
Features:
- Automatic wildcard SSL certificate generation
- Support for custom domains with automatic DNS configuration
- Lambda@Edge function for intelligent path rewriting
- Conservative caching policy (60s default TTL)
- Stores configuration in SSM Parameter Store for use by
StaticContent
Basic Usage (CloudFront Domain Only):
import { StaticHosting } from '@codedrifters/constructs';
import { Stack } from 'aws-cdk-lib';
const hostingStack = new Stack(app, 'HostingStack', { env });
const hosting = new StaticHosting(hostingStack, 'static-hosting', {
description: 'My static website',
});With Custom Domain:
import { StaticHosting } from '@codedrifters/constructs';
import { Stack, RemovalPolicy } from 'aws-cdk-lib';
const hostingStack = new Stack(app, 'HostingStack', { env });
const hosting = new StaticHosting(hostingStack, 'static-hosting', {
description: 'My static website',
staticDomainProps: {
baseDomain: 'example.com',
hostedZoneAttributes: {
hostedZoneId: 'Z1234567890ABC',
zoneName: 'example.com',
},
},
privateBucketProps: {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
},
});Properties:
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| description | string | undefined | Short description for traceability |
| staticDomainProps | StaticDomainProps | undefined | Domain configuration (optional) |
| bucketArnParamName | string | "/STATIC_WEBSITE/BUCKET_ARN" | SSM parameter name for bucket ARN |
| distributionDomainParamName | string | "/STATIC_WEBSITE/DISTRIBUTION_DOMAIN" | SSM parameter name for distribution domain |
| distributionIDParamName | string | "/STATIC_WEBSITE/DISTRIBUTION_ID" | SSM parameter name for distribution ID |
| privateBucketProps | PrivateBucketProps | undefined | Props to pass to the S3 bucket |
StaticDomainProps:
| Property | Type | Description |
|----------|------|-------------|
| baseDomain | string | The base domain (e.g., example.com) |
| hostedZoneAttributes | HostedZoneAttributes | Hosted zone ID and zone name |
Outputs:
The construct exposes:
fullDomain: string- The full domain name (custom domain if provided, otherwise CloudFront domain)
SSM Parameters Created:
The construct automatically creates SSM parameters that can be referenced by StaticContent:
- Bucket ARN (default:
/STATIC_WEBSITE/BUCKET_ARN) - CloudFront Distribution Domain (default:
/STATIC_WEBSITE/DISTRIBUTION_DOMAIN) - CloudFront Distribution ID (default:
/STATIC_WEBSITE/DISTRIBUTION_ID)
StaticContent
Deploys static content from a local directory to an S3 bucket. This construct is designed to work with StaticHosting and supports branch-based deployment paths for PR and feature branch previews.
Features:
- Deploys files from a local directory to S3
- Supports branch-based path prefixes (e.g.,
feature-123.example.com/) - Automatically retrieves bucket ARN from SSM Parameter Store
- Configurable destination directory within the bucket
How Branch-Based Deployment Works:
The construct uses the current git branch name to create unique deployment paths. This allows multiple branches to deploy to the same bucket without conflicts:
S3 Bucket Structure:
├── example.com/ → Production/main branch
├── feature-123.example.com/ → Feature branch
├── pr-456.example.com/ → Pull request
└── stage.example.com/ → Staging branchBasic Usage:
import { StaticContent, StaticHosting } from '@codedrifters/constructs';
import { Stack } from 'aws-cdk-lib';
// First, create the hosting infrastructure
const hostingStack = new Stack(app, 'HostingStack', { env });
const hosting = new StaticHosting(hostingStack, 'static-hosting', {
staticDomainProps: {
baseDomain: 'example.com',
hostedZoneAttributes: {
hostedZoneId: 'Z1234567890ABC',
zoneName: 'example.com',
},
},
});
// Then, deploy content in a separate stack
const contentStack = new Stack(app, 'ContentStack', { env });
contentStack.node.addDependency(hostingStack);
new StaticContent(contentStack, 'static-content', {
contentSourceDirectory: 'dist', // Local directory with built files
contentDestinationDirectory: '/', // Deploy to root of bucket path
fullDomain: hosting.fullDomain, // Use domain from StaticHosting
});With Custom Subdomain:
new StaticContent(contentStack, 'static-content', {
contentSourceDirectory: 'dist',
contentDestinationDirectory: '/',
fullDomain: hosting.fullDomain,
subDomain: 'staging', // Override git branch detection
bucketArnParamName: '/STATIC_WEBSITE/BUCKET_ARN', // Custom param name
});Properties:
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| contentSourceDirectory | string | Required | Absolute path to directory containing files to deploy |
| contentDestinationDirectory | string | Required | Directory within bucket to place content (should start with /) |
| fullDomain | string | Required | Full domain name (from StaticHosting.fullDomain) |
| subDomain | string | Git branch name | Subdomain prefix (defaults to current git branch) |
| bucketArnParamName | string | "/STATIC_WEBSITE/BUCKET_ARN" | SSM parameter name for bucket ARN |
Path Construction:
The construct creates a unique path prefix using: {subDomain}.{fullDomain}
For example:
- Branch:
feature-123, Domain:example.com→ Path:feature-123.example.com/ - Branch:
main, Domain:example.com→ Path:main.example.com/(or justexample.com/if subdomain is empty)
Complete Example
Here's a complete example showing how to use StaticHosting and StaticContent together:
import { StaticContent, StaticHosting } from '@codedrifters/constructs';
import { App, RemovalPolicy, Stack } from 'aws-cdk-lib';
const app = new App();
const env = {
account: '123456789012',
region: 'us-east-1',
};
const baseDomain = 'example.com';
/*******************************************************************************
*
* Step 1: Create the hosting infrastructure
*
* This creates the S3 bucket, CloudFront distribution, SSL certificate,
* and DNS records.
*
******************************************************************************/
const hostingStack = new Stack(
app,
`static-hosting-dev-${env.account}-${env.region}`,
{ env }
);
const hosting = new StaticHosting(hostingStack, 'static-hosting', {
description: 'My static website',
privateBucketProps: {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
},
staticDomainProps: {
baseDomain,
hostedZoneAttributes: {
hostedZoneId: 'Z1234567890ABC',
zoneName: baseDomain,
},
},
});
/*******************************************************************************
*
* Step 2: Deploy static content
*
* This deploys files from a local directory to the S3 bucket created above.
* The content stack must depend on the hosting stack to ensure the bucket
* exists before deployment.
*
******************************************************************************/
const contentStack = new Stack(
app,
`static-content-dev-${env.account}-${env.region}`,
{ env }
);
// Ensure hosting stack is created first
contentStack.node.addDependency(hostingStack);
new StaticContent(contentStack, 'static-content', {
contentSourceDirectory: 'src/website', // Path to your built website files
contentDestinationDirectory: '/', // Deploy to root
fullDomain: hosting.fullDomain, // Use the domain from StaticHosting
});
app.synth();Deployment Flow:
- Deploy the hosting stack first:
cdk deploy static-hosting-dev-* - This creates the S3 bucket, CloudFront distribution, SSL certificate, and DNS records
- Deploy the content stack:
cdk deploy static-content-dev-* - This uploads your static files to the S3 bucket
- Your website is now live at your domain!
Branch-Based Deployments:
When deploying from different git branches, the StaticContent construct automatically uses the branch name as a subdomain prefix. This allows you to have:
mainbranch →example.comfeature-123branch →feature-123.example.compr-456branch →pr-456.example.com
All using the same S3 bucket and CloudFront distribution!
API Reference
Exports
The package exports the following:
Constructs:
PrivateBucket- Secure S3 bucketStaticHosting- Complete static hosting solutionStaticContent- Static content deployment
Type Definitions
PrivateBucketProps
- Extends
BucketPropsfromaws-cdk-lib/aws-s3 - All standard S3 bucket properties are supported
- Security settings are enforced and cannot be overridden
StaticHostingProps
- Extends
StackPropsfromaws-cdk-lib - See StaticHosting section for full property list
StaticContentProps
- See StaticContent section for full property list
StaticDomainProps
baseDomain: string- Base domain namehostedZoneAttributes: HostedZoneAttributes- Route53 hosted zone attributes
Further Documentation
AWS CDK Resources
- AWS CDK Developer Guide - Comprehensive guide to AWS CDK
- AWS CDK API Reference - Complete API documentation
- AWS CDK Construct Library - All available constructs
AWS Service Documentation
- Amazon S3 Documentation - S3 service documentation
- Amazon CloudFront Documentation - CloudFront CDN documentation
- AWS Certificate Manager - SSL/TLS certificate management
- Amazon Route53 - DNS service documentation
Package Information
- NPM Package - View on NPM
- GitHub Repository - Source code
Note: This package is designed for use with AWS CDK v2. Make sure you're using compatible versions of aws-cdk-lib and constructs.
