How to create a TypeScript Lambda with AWS SAM
How to create a TypeScript Lambda with AWS SAM. Initialize the project, compile with esbuild, test locally, and deploy to AWS in minutes without pain.
Straight to it: create a TypeScript Lambda with AWS SAM. By the end, you’ll have a TypeScript Lambda initialized with SAM, built with esbuild, tested locally via Docker, and deployed to AWS with a ready-to-hit curl endpoint.
No mystery templates, no magic. You’ll know what each step does and why. Copy, paste, done.
Requirements
- AWS account with permissions to create IAM roles, Lambda, and API Gateway.
- AWS CLI configured with default credentials. Verify with
aws sts get-caller-identity. - AWS SAM CLI installed and on PATH. Verify with
sam --version. - Docker running to use
sam local. - Node.js LTS installed. Prefer the latest LTS.
Step 1: create a TypeScript Lambda with AWS SAM
I start from an empty project so you don’t depend on hidden scaffolds. Create the folder and enter it.
mkdir my-lambda-ts && cd my-lambda-tsIf you don’t have Node LTS yet:
Linux/macOS with nvm:
nvm install --lts
nvm use --lts
node -vWindows with winget:
winget install OpenJS.NodeJS.LTS
node -vStep 2: initialize project and dependencies
Create a minimal package.json and add TypeScript, types, and esbuild as dev dependencies. Version ranges are examples; newer is fine.
npm init -y
npm i -D typescript esbuild @types/aws-lambdaGenerate a basic tsconfig.json:
npx tsc --init --outDir dist --rootDir . --esModuleInterop --resolveJsonModule --target ES2020 --module CommonJSTune it for Lambda. Open tsconfig.json and use this:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"outDir": "dist"
},
"exclude": ["node_modules", ".aws-sam", "dist"]
}Step 3: Lambda code in TypeScript
Create src/app.ts with a simple HTTP handler. It returns JSON and reads a name query param.
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const name = event.queryStringParameters?.name || 'world';
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: `Hello ${name} from TypeScript + SAM` })
};
};Step 4: SAM template with esbuild
Here’s the good part. SAM will build with esbuild, package, and deploy. Create template.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: TypeScript Lambda with SAM and esbuild
Globals:
Function:
Runtime: nodejs20.x
Timeout: 5
MemorySize: 128
Environment:
Variables:
NODE_OPTIONS: --enable-source-maps
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: app.handler
Architectures:
- arm64
Events:
Api:
Type: Api
Properties:
Path: /hello
Method: get
Metadata:
BuildMethod: esbuild
BuildProperties:
Minify: true
Sourcemap: true
Target: node20
EntryPoints:
- src/app.ts
External:
- aws-sdk
Outputs:
ApiUrl:
Description: API Gateway endpoint
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello"Cost/perf tip: arm64 tends to be cheaper than x86_64. If you rely on native binaries without ARM builds, switch to x86_64.
Step 5: handy npm scripts
Not mandatory, but faster. Open package.json and add these scripts:
{
"name": "my-lambda-ts",
"version": "1.0.0",
"type": "commonjs",
"scripts": {
"build": "sam build",
"local:invoke": "sam local invoke HelloFunction --event events/hello.json",
"local:api": "sam local start-api",
"deploy": "sam deploy --guided"
},
"devDependencies": {
"@types/aws-lambda": "^8.10.0",
"esbuild": "^0.21.0",
"typescript": "^5.6.0"
},
"dependencies": {}
}Create a test event at events/hello.json:
{
"resource": "/hello",
"path": "/hello",
"httpMethod": "GET",
"queryStringParameters": { "name": "SAM" },
"requestContext": {
"resourcePath": "/hello",
"httpMethod": "GET",
"path": "/Prod/hello"
},
"body": null,
"isBase64Encoded": false
}Step 6: build with SAM
This triggers esbuild and packages the artifact. Make sure Docker is running if you’ll test locally.
sam buildStep 7: test locally with sam local invoke
Direct invocation with the test event:
sam local invoke HelloFunction --event events/hello.jsonExpected output:
{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\"message\":\"Hello SAM from TypeScript + SAM\"}"}Or spin up a local API and curl it:
sam local start-apiIn another terminal:
curl "http://127.0.0.1:3000/hello?name=Local"Response:
{"message":"Hello Local from TypeScript + SAM"}Step 8: deploy to AWS
For the first time, use the guided flow so SAM stores parameters. It will ask for stack name, region, IAM permissions, etc.
sam deploy --guidedAt the end, SAM prints the Outputs. You should see ApiUrl. Copy it, we’ll use it now.
Verify it works
Hit the endpoint printed by SAM in the ApiUrl output (example):
curl "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/hello?name=Cloud"Expected output:
{"message":"Hello Cloud from TypeScript + SAM"}Common errors and fixes
-
Error: Docker is not running. Failed to connect to Docker daemonFix: start Docker Desktop or the Docker service.
sam localrelies on Docker to emulate Lambda. -
Build Failed: NodejsNpmEsbuildBuilder:EsbuildFailedFix: ensure
esbuildis a devDependency, removenode_modulesandpackage-lock.jsonif needed and runnpm ci. Verifynode -vis LTS. -
An error occurred (AccessDeniedException) when calling the CreateChangeSetFix: run
sam deploy --guidedand allow creating/using IAM roles. Use credentials with CloudFormation, IAM, Lambda, and API Gateway permissions. -
curlreturns 403 or 404Fix: use exactly the URL from
ApiUrland don’t forget/Prod/hello. If you changedPathin the template, update curl accordingly.
FAQ
How do I switch to x86_64 if I use native binaries
Edit the template and set Architectures to x86_64. Rebuild and redeploy.
Architectures:
- x86_64Can I set environment variables for my Lambda
Yes. Add them under Globals.Function.Environment.Variables or the function’s Properties.Environment and read with process.env.
Environment:
Variables:
STAGE: prodconst stage = process.env.STAGE ?? 'dev';How do I add another HTTP route
Add another Api event with a different Path or define another function. For a single handler, route by event.path or event.resource.
Events:
HelloApi:
Type: Api
Properties:
Path: /hello
Method: get
PingApi:
Type: Api
Properties:
Path: /ping
Method: getWhich Node.js runtime should I use
Go with the latest LTS supported by Lambda and set it in Globals.Function.Runtime. When a new LTS becomes available, change one line and rebuild.
Notes and next steps
If you want to peek under Lambda’s hood, check how Lambda orchestrates MicroVMs with Durable Functions. And if you care about long-running tasks, here’s what changed when AWS Lambda doubled its max timeout to 30 minutes.
My take: SAM saves a ton of time, but it won’t save you from yourself. If local builds pass but the cloud fails, it’s usually IAM or an environment assumption. And yes, PATH bites again. PS: I won’t promise you won’t curse at Docker, only that you’ll curse less.