How to create a TypeScript Lambda with AWS SAM

Tutorials New By 5 min read

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.

Bash
mkdir my-lambda-ts && cd my-lambda-ts

If you don’t have Node LTS yet:

Linux/macOS with nvm:

Bash
nvm install --lts
nvm use --lts
node -v

Windows with winget:

PowerShell
winget install OpenJS.NodeJS.LTS
node -v

Step 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.

Bash
npm init -y
npm i -D typescript esbuild @types/aws-lambda

Generate a basic tsconfig.json:

Bash
npx tsc --init --outDir dist --rootDir . --esModuleInterop --resolveJsonModule --target ES2020 --module CommonJS

Tune it for Lambda. Open tsconfig.json and use this:

JSON
{
  "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.

TypeScript
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:

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:

JSON
{
  "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:

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.

Bash
sam build

Step 7: test locally with sam local invoke

Direct invocation with the test event:

Bash
sam local invoke HelloFunction --event events/hello.json

Expected output:

Texto
{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\"message\":\"Hello SAM from TypeScript + SAM\"}"}

Or spin up a local API and curl it:

Bash
sam local start-api

In another terminal:

Bash
curl "http://127.0.0.1:3000/hello?name=Local"

Response:

Texto
{"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.

Bash
sam deploy --guided

At 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):

Bash
curl "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/hello?name=Cloud"

Expected output:

Texto
{"message":"Hello Cloud from TypeScript + SAM"}

Common errors and fixes

  • Error: Docker is not running. Failed to connect to Docker daemon

    Fix: start Docker Desktop or the Docker service. sam local relies on Docker to emulate Lambda.

  • Build Failed: NodejsNpmEsbuildBuilder:EsbuildFailed

    Fix: ensure esbuild is a devDependency, remove node_modules and package-lock.json if needed and run npm ci. Verify node -v is LTS.

  • An error occurred (AccessDeniedException) when calling the CreateChangeSet

    Fix: run sam deploy --guided and allow creating/using IAM roles. Use credentials with CloudFormation, IAM, Lambda, and API Gateway permissions.

  • curl returns 403 or 404

    Fix: use exactly the URL from ApiUrl and don’t forget /Prod/hello. If you changed Path in 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.

YAML
Architectures:
  - x86_64

Can 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.

YAML
Environment:
  Variables:
    STAGE: prod
TypeScript
const 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.

YAML
Events:
  HelloApi:
    Type: Api
    Properties:
      Path: /hello
      Method: get
  PingApi:
    Type: Api
    Properties:
      Path: /ping
      Method: get

Which 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.

Related posts

More categories