The easiest way to deploy an API on AWS Lambda with modern web frameworks.
- Server-side logic with AWS Lambda for dynamic content and API handling
- Amazon API Gateway for creating, deploying, and managing secure APIs at any scale.
- Publicly available by a custom domain (or subdomain) via Route53 and SSL via Certificate Manager
- Environment variables for Lambda can be securely stored and managed using AWS Secrets Manager.
- Build and deploy with Github Actions
This library supports three ways to deploy your API:
- Standard Lambda and API Gateway.
- Node.js runtime container image on Lambda.
- Bun runtime container image on Lambda.
Supported frameworks:
- Express.js
- Hono
- NestJS
- Fastify
- Koa
- AdonisJS
- Sails.js
- LoopBack
- Feathers
- Restify
- Any web application framework
You need an AWS account to create and deploy the required resources for the site on AWS.
Before you begin, make sure you have the following:
-
Node.js and npm: Ensure you have Node.js (v20 or later) and npm installed.
-
AWS CLI: Install and configure the AWS Command Line Interface.
-
AWS CDK: Install the AWS CDK globally
npm install -g aws-cdk
- Before deploying, bootstrap your AWS environment:
cdk bootstrap aws://your-aws-account-id/us-east-1
This package uses the npm
package manager and is an ES6+ Module.
Navigate to your project directory and install the package and its required dependencies.
Your package.json
must also contain tsx
and this specific version of aws-cdk-lib
:
npm i tsx @thunderso/cdk-functions --save-dev
-
Login into the AWS console and note the
Account ID
. You will need it in the configuration step. -
Run the following commands to create the required CDK stack entrypoint at
stack/index.ts
.
mkdir stack
cd stack
touch index.ts
You should adapt the file to your project's needs.
Note
Use different filenames such as production.ts
and dev.ts
for environments.
//stack/index.ts
import { Cdk, FunctionStack, type FunctionProps } from '@thunderso/cdk-functions';
const fnProps: FunctionProps = {
// Set your AWS environment
env: {
account: 'your-account-id',
region: 'us-east-1',
},
// Label your infrastructure
application: 'your-application-id',
service: 'your-service-id',
environment: 'dev',
rootDir: '', // supports monorepos e.g. api/
// Configure the function
functionProps: {
codeDir: 'dist/',
handler: 'index.handler',
},
};
new FunctionStack(
new Cdk.App(),
`${fnProps.application}-${fnProps.service}-${fnProps.environment}-stack`,
fnProps
);
By running the following script, the CDK stack will be deployed to AWS.
npx cdk deploy --all --app="npx tsx stack/index.ts"
In your GitHub repository, add a new workflow file under .github/workflows/deploy.yml
with the following content:
name: Deploy Function to AWS
on:
push:
branches:
- main # or the branch you want to deploy from
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
- name: Deploy to AWS
run: |
npx cdk deploy --require-approval never --all --app="npx tsx stack/index.ts"
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_DEFAULT_REGION: 'us-east-1' # or your preferred region
Add AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
as repository secrets in GitHub. These should be the access key and secret for an IAM user with permissions to deploy your stack.
If you want to destroy the stack and all its resources (including storage, e.g., access logs), run the following script:
npx cdk destroy --all --app="npx tsx stack/index.ts"
- Create a hosted zone in Route53 for the desired domain, if you don't have one yet.
This is required to create DNS records for the domain to make the app publicly available on that domain. On the hosted zone details you should see the Hosted zone ID
of the hosted zone.
- Request a public regional certificate in the AWS Certificate Manager (ACM) for the desired domain in the same region as the function and validate it, if you don't have one yet.
This is required to provide the app via HTTPS on the public internet. Take note of the displayed ARN
for the certificate.
Important
The certificate must be issued in the same region as the function.
// stack/index.ts
const fnProps: FunctionProps = {
// ... other props
domain: 'api.example.com',
hostedZoneId: 'XXXXXXXXXXXXXXX',
regionalCertificateArn: 'arn:aws:acm:us-east-1:123456789012:certificate/abcd1234-abcd-1234-abcd-1234abcd1234',
};
Each configuration property provides a means to fine-tune your function’s performance and operational characteristics.
// stack/index.ts
import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda';
import { Cdk, FunctionStack, type FunctionProps } from '@thunderso/cdk-functions';
const fnProps: FunctionProps = {
// ... other props
functionProps: {
runtime: Runtime.NODEJS_20_X,
architecture: Architecture.ARM_64,
codeDir: 'dist',
handler: 'index.handler',
memorySize: 1792,
timeout: 10,
tracing: true,
include: ['package.json', 'package-lock.json'],
exclude: ['**/*.ts', '**/*.map'],
keepWarm: true
},
};
new FunctionStack(
new Cdk.App(),
`${fnProps.application}-${fnProps.service}-${fnProps.environment}-stack`,
fnProps
);
Specifies the runtime environment for the Lambda function, determining which Lambda runtime API versions are available to the function.
- Type:
Runtime
- Examples:
Runtime.NODEJS_20_X
,Runtime.PYTHON_3_8
- Default: The runtime defaults to
Runtime.NODEJS_20_X
.
Defines the instruction set architecture that the Lambda function supports.
- Type:
Architecture
- Examples:
Architecture.ARM_64
,Architecture.X86_64
- Default: The architecture defaults to
Architecture.ARM_64
.
Indicates the directory containing the Lambda function code.
- Type:
string
- Usage Example:
codeDir: 'dist'
- Default:
codeDir: ''
.
Specifies the function within your code that Lambda calls to start executing your function.
- Type:
string
- Usage Example:
handler: 'index.handler'
- Default:
handler: 'index.handler'
The amount of memory, in MB, allocated to the Lambda function.
- Type:
number
- Default: 1792 MB
- Usage Example:
memorySize: 512
The function execution time (in seconds) after which Lambda will terminate the running function.
- Type:
number
- Default: 10 seconds
- Usage Example:
timeout: 15
Enables or disables AWS X-Ray tracing for the Lambda function.
- Type:
boolean
- Default:
false
- Usage Example:
tracing: true
Lists the files to be included to the Docker context (your build output directory)
- Type:
string[]
- Usage Example:
exclude: ['package.json', 'bun.lock']
Lists the file patterns that should be excluded from the Lambda deployment package.
- Type:
string[]
- Usage Example:
exclude: ['*.test.js', 'README.md']
Enables an EventBridge rule to invoke the Lambda function every 5 minutes, helping to prevent cold starts by keeping the function warm.
- Type:
boolean
- Default:
false
- Usage Example:
keepWarm: true
Pass environment variables to your lambda function by:
-
variables
: Array of key-value pairs for plain environment variables. -
secrets
: Array of objects withkey
andresource
(Secrets Manager ARN). The library automatically adds permissions for Lambda to read these secrets.
To create a plaintext secret in AWS Secrets Manager using the AWS CLI:
aws secretsmanager create-secret --name "your-secret-name" --secret-string "your-secret-value"
// stack/index.ts
const fnProps: FunctionProps = {
// ... other props
functionProps: {
// ... other props
variables: [
{ VITE_API_URL: 'https://api.example.com' },
{ VITE_ANALYTICS_ID: 'UA-XXXXXX' }
],
secrets: [
{
key: 'API_URL',
resource: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:/my-app/API_URL-abc123'
},
{
key: 'API_KEY',
resource: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:/my-app/API_KEY-def456'
},
],
}
};
When configuring AWS Lambda functions, understanding scaling properties is essential for efficient resource management and cost optimization. The two primary scaling properties you can configure are reservedConcurrency
and provisionedConcurrency
.
// stack/index.ts
const fnProps: FunctionProps = {
// ... other props
functionProps: {
// ... other props
reservedConcurrency: 5,
provisionedConcurrency: 10,
},
};
Reserved concurrency sets a limit on the number of instances of the function that can run simultaneously. It ensures that your function has access to a specified amount of concurrent executions, preventing it from being throttled if account-level concurrency limits are reached.
- Use Case: This is useful when you want to have predictable execution patterns or ensure other functions don't consume all available concurrency.
- Example:
reservedConcurrency: 5
Provisioned concurrency keeps a set of pre-initialized environments ready to respond immediately to incoming requests. This helps in reducing latency and eliminating cold starts when the function is triggered.
- Use Case: Ideal for latency-sensitive applications where response time is critical.
- Example:
provisionedConcurrency: 10
While both reserved and provisioned concurrency deal with execution limits, they serve different purposes. Reserved concurrency guarantees a portion of the total function pool across your AWS account, while provisioned concurrency is specifically about warming up a set number of function instances to achieve low-latency execution.
CDK-Functions supports deploying your API as a Lambda container image, allowing you to use custom runtimes or package dependencies that exceed the Lambda zip package size limit. This is especially useful for advanced use cases or when using alternative runtimes like Bun.
To deploy your function using a Node.js container image:
- Create a Dockerfile (e.g.,
Dockerfile.node
) in your project root:
FROM public.ecr.aws/lambda/nodejs:22 AS base
WORKDIR ${LAMBDA_TASK_ROOT}
# Copy project files, install dependencies and build
COPY . .
RUN npm i --omit=dev
RUN npm run build
FROM public.ecr.aws/lambda/nodejs:22
WORKDIR ${LAMBDA_TASK_ROOT}
# Copy the code directory (dist)
COPY --from=base /var/task/dist/* ./
# Copy node_modules (optional)
COPY --from=base /var/task/node_modules node_modules
# Set the Lambda handler
CMD [ "index.handler" ]
Depending on your framework, there may not be an index.js
file in your build output which exports a handler
. Ensure your entrypoint is correct.
- Configure your stack to use the Dockerfile:
// stack/node.ts
import { Cdk, FunctionStack, type FunctionProps } from '@thunderso/cdk-functions';
const fnProps: FunctionProps = {
// ... other props ...
functionProps: {
dockerFile: 'Dockerfile.node',
},
};
new FunctionStack(
new Cdk.App(),
`${fnProps.application}-${fnProps.service}-${fnProps.environment}-stack`,
fnProps
);
- Deploy as usual:
npx cdk deploy --all --app="npx tsx stack/node.ts"
You can also deploy your Lambda using the Bun runtime by building a custom container image.
- Create a Dockerfile (e.g.,
Dockerfile.bun
):
# Bun image
FROM oven/bun:latest AS bun
WORKDIR /tmp
## Install the bun dependencies
RUN apt-get update && apt-get install -y curl
RUN curl -fsSL https://raw.githubusercontent.com/oven-sh/bun/main/packages/bun-lambda/runtime.ts -o /tmp/runtime.ts
RUN bun install aws4fetch
RUN bun build --compile runtime.ts --outfile bootstrap
# Builder image
FROM oven/bun:latest AS base
WORKDIR /tmp
## Copy project files, install dependencies and build
COPY . .
RUN bun install
RUN bun run build
# Runtime image
FROM public.ecr.aws/lambda/provided:al2023
WORKDIR ${LAMBDA_TASK_ROOT}
## Copy bun + bootstrap from the builder image
COPY --from=bun /usr/local/bin/bun /opt/bun
COPY --from=bun /tmp/bootstrap ${LAMBDA_RUNTIME_DIR}
## Copy the code directory (dist)
COPY --from=base /tmp/dist/* ./
## Copy node_modules
COPY --from=base /tmp/node_modules node_modules
## Copy the lambda entrypoint
COPY --from=base /tmp/lambda-bun.js lambda-bun.js
## Set our handler method
CMD [ "lambda-bun.fetch" ]
- Create the Bun Lambda handler
Bun requires a fetch-compatible handler because Bun’s server runtime is designed to be compatible with the Fetch API, which is a standard web API for handling HTTP requests and responses. In Bun, serverless functions or HTTP handlers are expected to export a function (often called fetch) that matches the signature:
async function fetch(request: Request): Promise<Response>
This approach allows Bun to handle HTTP requests in a way that is consistent with modern web standards, making it easier to share code between server and client, and to integrate with frameworks like Hono or Nitro that also use the Fetch API model.
Create a handler file lambda-bun.js
in your root directory.
// lambda-bun.js (for Bun + Hono + Nitro)
const { handler } = require('./index.js');
exports.fetch = handler;
- Configure your stack:
// stack/bun.ts
import { Cdk, FunctionStack, type FunctionProps } from '@thunderso/cdk-functions';
const fnProps: FunctionProps = {
// ... other props ...
functionProps: {
dockerFile: 'Dockerfile.bun',
},
};
new FunctionStack(
new Cdk.App(),
`${fnProps.application}-${fnProps.service}-${fnProps.environment}-stack`,
fnProps
);
- Deploy as usual:
npx cdk deploy --all --app="bunx tsx stack/bun.ts"
- The
dockerFile
property infunctionProps
tells CDK-Functions to build and deploy your Lambda using the specified Dockerfile. - In order to use the standard Lambda, run
npm run build
to build your project before running the deployment script. Thedist
folder generated by the build step is used as the code directory for the Lambda. - On container Lambdas, the entire project directory is used as Docker context. The build step is not required as the package installation and build are done inside the Dockerfile.
runtime
,architecture
,codeDir
,handler
,include
,exclude
are not required.timeout
,tracing
,keepWarm
,variables
,secrets
and scaling properties work as expected.- You can pass build arguments to your Docker build using the
dockerBuildArgs
property.
For more information, refer to the CDK documentation on container images.