---
title: "How to create a TypeScript Lambda with AWS SAM | Daniel Segovia"
description: "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."
url: https://danielsegovia.com/en/tutorials/create-typescript-lambda-aws-sam/
lang: en
author: "Daniel Segovia"
published: 2026-11-27T14:35:00.000Z
modified: 2026-11-27T13:17:04.101Z
section: "Tutorials"
---

1.  [Home](https://danielsegovia.com/en/)
2.  [Tutorials](https://danielsegovia.com/en/tutorials/)
3.  How to create a TypeScript Lambda with AWS SAM

# How to create a TypeScript Lambda with AWS SAM

[Tutorials](https://danielsegovia.com/en/tutorials/) New By [Daniel Segovia](https://danielsegovia.com/en/about/) · November 27, 2026 · 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.

In this post

1.  [Requirements](#requirements)
2.  [Step 1: create a TypeScript Lambda with AWS SAM](#step-1-create-a-typescript-lambda-with-aws-sam)
3.  [Step 2: initialize project and dependencies](#step-2-initialize-project-and-dependencies)
4.  [Step 3: Lambda code in TypeScript](#step-3-lambda-code-in-typescript)
5.  [Step 4: SAM template with esbuild](#step-4-sam-template-with-esbuild)
6.  [Step 5: handy npm scripts](#step-5-handy-npm-scripts)
7.  [Step 6: build with SAM](#step-6-build-with-sam)
8.  [Step 7: test locally with sam local invoke](#step-7-test-locally-with-sam-local-invoke)
9.  [Step 8: deploy to AWS](#step-8-deploy-to-aws)
10.  [Verify it works](#verify-it-works)
11.  [Common errors and fixes](#common-errors-and-fixes)
12.  [FAQ](#faq)
13.  [Notes and next steps](#notes-and-next-steps)

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:

```text
{"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:

```text
{"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:

```text
{"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](https://danielsegovia.com/en/architecture/aws-lambda-durable-functions-microvms-orchestration/). And if you care about long-running tasks, here’s what changed when [AWS Lambda doubled its max timeout to 30 minutes](https://danielsegovia.com/en/architecture/aws-lambda-max-timeout-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.

## Tags

-   [#AWS Lambda](https://danielsegovia.com/en/tags/aws-lambda/)
-   [#TypeScript](https://danielsegovia.com/en/tags/typescript/)
-   [#AWS SAM](https://danielsegovia.com/en/tags/aws-sam/)
-   [#Node.js](https://danielsegovia.com/en/tags/node-js/)

[See all tags →](https://danielsegovia.com/en/tags/)

## Related posts

-   [Invoke Amazon Bedrock from Node.js: step-by-step guide](https://danielsegovia.com/en/tutorials/invoke-amazon-bedrock-nodejs/)
    
    Invoke Amazon Bedrock from Node.js using SDK v3. Set up IAM, call the Converse API, and handle throttling so your app doesn’t faceplant under load.
    
    6 min read
-   [Create an MCP server in TypeScript: step-by-step guide](https://danielsegovia.com/en/tutorials/create-mcp-server-typescript/)
    
    Learn how to create an MCP server in TypeScript, expose tools and resources with the official SDK, and test it with a compatible client.
    
    6 min read
-   [Install Node.js with nvm and switch versions step by step](https://danielsegovia.com/en/tutorials/install-nodejs-nvm-switch-version/)
    
    Install Node.js with nvm on Linux, macOS, and Windows. I'll show you how to install LTS, set a default version, and use .nvmrc per project.
    
    5 min read

## More categories

-   ### [Tutorials](https://danielsegovia.com/en/tutorials/)
    
    [How to create a TypeScript Lambda with AWS SAM](https://danielsegovia.com/en/tutorials/create-typescript-lambda-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.
    
    New 5 min read
    
-   ### [News](https://danielsegovia.com/en/news/)
    
    [Huawei speeds chip design; Nvidia slows ASEAN server flows](https://danielsegovia.com/en/news/huawei-speeds-chip-design-nvidia-slows-asean-servers/)
    
    Huawei pushes its homegrown chip-design stack while Nvidia halts AI server shipments in ASEAN. If you bet on one vendor, map risk and ship a plan B.
    
    New 3 min read
    
-   ### [Artificial Intelligence](https://danielsegovia.com/en/artificial-intelligence/)
    
    [OpenAI/Anthropic lock data; China turns to Google and Meta](https://danielsegovia.com/en/artificial-intelligence/openai-anthropic-lock-data-china-google-meta/)
    
    OpenAI and Anthropic restricted data and Chinese players look to Google and Meta. Time to harden pipelines: clear licenses and a data plan B.
    
    New 3 min read
    
-   ### [Security](https://danielsegovia.com/en/security/)
    
    [GoodGuys phishing mimics brands to steal Google/Okta](https://danielsegovia.com/en/security/goodguys-phishing-google-okta-paid-interviews/)
    
    GoodGuys lures with paid interviews to steal corporate Google/Okta creds. Active since October. Priorities: FIDO MFA, phishing drills, and tight SSO control.
    
    New 3 min read
    
-   ### [Architecture](https://danielsegovia.com/en/architecture/)
    
    [Cloudflare toggle for AI-agent search, and you pay the bill](https://danielsegovia.com/en/architecture/cloudflare-toggle-ai-agent-search-cost-privacy/)
    
    Cloudflare added a toggle for AI agents to search your site. You pay the query bill. Good DX, new risks to budgets and privacy. Add access controls and limits.
    
    New 3 min read
    
-   ### [Business](https://danielsegovia.com/en/business/)
    
    [AI infrastructure spend could hit $1T in 2026: now what](https://danielsegovia.com/en/business/ai-infrastructure-spend-2026-1t/)
    
    AI infra investment could reach $1T in 2026. With a $1.8T funding gap through 2030, it’s time to lock budgets, renegotiate contracts and squeeze unit costs.
    
    New 3 min read

---

Sitio: https://danielsegovia.com/ · Índice para agentes: https://danielsegovia.com/llms.txt · Sitemap: https://danielsegovia.com/sitemap.xml
