Serverless Functions in TypeScript: AWS Lambda from A to Z

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Serverless Functions in TypeScript with AWS Lambda

\n\n

Serverless architecture has become the standard for modern cloud development. AWS Lambda allows you to run code without managing servers, while TypeScript adds strict typing and development convenience. In this article, we will cover the entire process: from creating your first function to deploying it to production. You will learn how to write efficient serverless functions in TypeScript, work with triggers, and handle errors.

\n\n

Serverless functions are ideal for microservices, event processing, webhooks, and background tasks. TypeScript makes the code safer and more predictable, which is critical for production solutions.

\n\n

1. Setting Up the Environment for AWS Lambda with TypeScript

\n\n

Before starting, install the necessary tools. You will need Node.js (version 18+), npm, and AWS CLI.

\n\n

1.1. Installing Dependencies

\n\n
npm init -y\nnpm install -D typescript @types/node @aws-sdk/client-lambda\nnpm install aws-lambda @types/aws-lambda\n
\n\n

1.2. TypeScript Configuration

\n\n

Create a tsconfig.json file with settings for Lambda:

\n\n
{\n  "compilerOptions": {\n    "target": "ES2020",\n    "module": "commonjs",\n    "lib": ["ES2020"],\n    "outDir": "./dist",\n    "rootDir": "./src",\n    "strict": true,\n    "esModuleInterop": true,\n    "skipLibCheck": true,\n    "forceConsistentCasingInFileNames": true,\n    "resolveJsonModule": true,\n    "declaration": true,\n    "declarationMap": true,\n    "sourceMap": true\n  },\n  "include": ["src/**/*"],\n  "exclude": ["node_modules", "dist"]\n}\n
\n\n

1.3. Installing AWS CLI

\n\n

Download and configure AWS CLI from the official source. After installation, run:

\n\n
aws configure\n
\n\n

Enter your Access Key ID, Secret Access Key, region (e.g., us-east-1), and output format (json).

\n\n

2. Creating Your First Serverless Function in TypeScript

\n\n

The project structure should look like this:

\n\n
my-lambda-project/\n├── src/\n│   └── handler.ts\n├── dist/\n├── tsconfig.json\n├── package.json\n└── .gitignore\n
\n\n

2.1. Basic Lambda Handler

\n\n

Create a file src/handler.ts with a simple function:

\n\n
import { Context, APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';\n\ninterface HelloResponse {\n  message: string;\n  timestamp: string;\n  eventType: string;\n}\n\nexport const handler = async (\n  event: APIGatewayProxyEvent,\n  context: Context\n): Promise<APIGatewayProxyResult> => {\n  console.log('Event:', JSON.stringify(event, null, 2));\n  console.log('Context:', context);\n\n  const response: HelloResponse = {\n    message: 'Hello from AWS Lambda with TypeScript!',\n    timestamp: new Date().toISOString(),\n    eventType: event.httpMethod || 'UNKNOWN'\n  };\n\n  return {\n    statusCode: 200,\n    headers: {\n      'Content-Type': 'application/json',\n      'Access-Control-Allow-Origin': '*'\n    },\n    body: JSON.stringify(response)\n  };\n};\n
\n\n

2.2. Compiling TypeScript

\n\n

Add scripts to package.json:

\n\n
"scripts": {\n  "build": "tsc",\n  "watch": "tsc --watch",\n  "clean": "rm -rf dist"\n}\n
\n\n

Run the build:

\n\n
npm run build\n
\n\n

Check that the dist folder contains the handler.js file.

\n\n

3. Deploying the Lambda Function to AWS

\n\n

There are several ways to deploy. Let's look at the simplest one — via AWS CLI.

\n\n

3.1. Packaging the Function

\n\n

Create a ZIP archive with the code:

\n\n
cd dist\nzip -r ../function.zip .\ncd ..\n
\n\n

3.2. Creating the Lambda Function

\n\n

Run the AWS CLI command:

\n\n
aws lambda create-function \\\n  --function-name hello-typescript \\\n  --runtime nodejs18.x \\\n  --role arn:aws:iam::Y                

Blogs

Book Recommendations