Cloud & Hosting (AWS)

AWS Lambda Setup & Deployment Guide

Run code without servers – write a Node.js function, test it locally with AWS SAM, deploy with an HTTP endpoint, environment variables and logs.

Updated Official documentation ↗

1. Introduction & use cases

AWS Lambda runs your code in response to events – an HTTP request, a file uploaded to S3, a queue message, a schedule – without you managing servers. You upload a function (Node.js, Python, Java, Go, .NET, Ruby or a container image), and AWS runs, scales and patches it. You pay per request and per millisecond of execution.

The AWS SAM (Serverless Application Model) CLI lets you define functions and APIs in a template, run them locally in Docker and deploy them with one command.

Where it is used

  • Serverless REST APIs (with API Gateway or Function URLs)
  • Processing S3 uploads (thumbnails, PDF text extraction)
  • Scheduled jobs and automation (EventBridge)
  • Queue/stream processing (SQS, Kinesis, DynamoDB streams)

2. Prerequisites

You needVersion / notes
AWS accountWith MFA on the root user and a non-root admin identity
AWS CLI v2Installed and configured – see the AWS guide
AWS SAM CLIInstall from the AWS docs (Windows MSI, macOS pkg/Homebrew, Linux zip)
DockerNeeded for sam local and some builds
Node.js LTSMatching a Lambda Node.js runtime

3. Local setup

  1. 1Install and check the SAM CLI

    Follow “Installing the AWS SAM CLI” for your OS, then verify. Make sure Docker is running for local testing.

    BASH
    sam --version
    docker info > /dev/null && echo "Docker OK"
  2. 2Create a project from a template

    Choose the Hello World example with a Node.js runtime.

    BASH
    sam init --name hello-lambda --runtime nodejs22.x --app-template hello-world --package-type Zip
    cd hello-lambda

4. Create & run a project

  1. 1Look at the handler

    Lambda calls the exported handler with the event. For HTTP events return statusCode, headers and a string body.

    hello-world/app.mjs
    export const handler = async (event) => {
      const name = event.queryStringParameters?.name ?? 'world';
      return {
        statusCode: 200,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: `Hello, ${name}!`, stage: process.env.STAGE }),
      };
    };
  2. 2Check the SAM template

    It defines the function, its runtime, memory/timeout, environment variables and the HTTP event.

    template.yaml
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Globals:
      Function:
        Timeout: 10
        MemorySize: 256
    Resources:
      HelloWorldFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: hello-world/
          Handler: app.handler
          Runtime: nodejs22.x
          Architectures: [arm64]
          Environment:
            Variables:
              STAGE: dev
          Events:
            HelloWorld:
              Type: Api
              Properties:
                Path: /hello
                Method: get
    Outputs:
      HelloApi:
        Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  3. 3Build and test locally

    sam local invoke runs the function once; start-api serves it on localhost:3000.

    BASH
    sam build
    sam local invoke HelloWorldFunction --event events/event.json
    sam local start-api
    curl "http://127.0.0.1:3000/hello?name=Asha"

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Set non-secret settings as function environment variables in the template. Read secrets from SSM Parameter Store or Secrets Manager at cold start (and cache them), granting the function’s role permission to read only those parameters.

template.yaml (Properties)
Environment:
  Variables:
    STAGE: prod
    TABLE_NAME: !Ref OrdersTable
    SECRET_ARN: arn:aws:secretsmanager:ap-south-1:123456789012:secret:app-xxxx

Key dependencies

Package / toolUsed for
AWS SAM CLIInit, local testing, build, deploy
@aws-sdk/* v3Call other AWS services from the function
API Gateway / Function URLHTTP entry points
CloudWatch LogsFunction logs (console.log)
Powertools for AWS LambdaLogging, tracing, metrics utilities
esbuildBundle TypeScript/ESM functions (SAM supports it)

Folder structure

project structure
hello-lambda/
├── hello-world/
│   ├── app.mjs        # handler
│   └── package.json
├── events/event.json  # sample event
├── template.yaml      # SAM / CloudFormation
└── samconfig.toml     # saved deploy settings

Essential commands

CommandWhat it does
sam buildBuild the functions
sam local invoke NAME -e event.jsonRun once locally
sam local start-apiLocal HTTP API
sam deploy --guidedFirst deploy (saves settings)
sam logs -n NAME --tailStream CloudWatch logs
sam deleteRemove the stack

6. Production deployment

Server & hosting requirements

RequirementRecommendation
IAMDeploying identity with CloudFormation/Lambda/IAM permissions; a least-privilege execution role per function
RuntimeA supported Lambda runtime (Node.js LTS versions)
Entry pointAPI Gateway (HTTP/REST API) or a Function URL
DomainAPI Gateway custom domain + regional ACM certificate
MonitoringCloudWatch logs, metrics and alarms on errors/throttles

Deployment steps

  1. 1Deploy with SAM

    The guided deploy asks for stack name, region and confirms IAM role creation, then saves answers in samconfig.toml.

    BASH
    sam build
    sam deploy --guided
    # next time simply:
    sam deploy
  2. 2Call the deployed API

    The URL is printed in the stack outputs.

    BASH
    curl "https://abc123.execute-api.ap-south-1.amazonaws.com/Prod/hello/?name=Asha"
  3. 3Simple alternative: a Function URL

    For a single function you can skip API Gateway and add a dedicated HTTPS endpoint.

    template.yaml (function Properties)
          FunctionUrlConfig:
            AuthType: NONE        # or AWS_IAM for private endpoints
  4. 4Use a custom domain

    Request an ACM certificate in the API’s region, create an API Gateway custom domain with it, map it to your API stage, and point DNS (Route 53 alias or CNAME) to the API Gateway domain name.

  5. 5Watch logs and set alarms

    Tail logs while testing; create CloudWatch alarms for Errors and Throttles.

    BASH
    sam logs -n HelloWorldFunction --stack-name hello-lambda --tail

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ sam local start-apiMounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] * Running on http://127.0.0.1:3000$ curl "http://127.0.0.1:3000/hello?name=Asha"{"message":"Hello, Asha!","stage":"dev"}$ sam deploy --guidedSuccessfully created/updated stack - hello-lambda in ap-south-1
Figure 1: terminal output of the sample AWS Lambda project (section 4).
1Handler + template2sam local test3sam build/deploy4API Gateway / URL5CloudWatch logs
Figure 2: production deployment flow (section 6).
hello-lambda/├── hello-world/│ ├── app.mjs # handler│ └── package.json├── events/event.json # sample event├── template.yaml # SAM / CloudFormation└── samconfig.toml # saved deploy settings
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Runtime.ImportModuleError: Cannot find module 'app'

Handler path mismatch. Handler: app.handler needs app.mjs/app.js in CodeUri exporting handler; use .mjs or "type": "module" for export syntax.

Task timed out after 3.00 seconds

Raise Timeout and check for slow external calls; reuse SDK clients and DB connections outside the handler.

AccessDeniedException calling another AWS service

Add the needed permission to the function’s execution role (SAM policy templates such as S3ReadPolicy).

API returns 502 Bad Gateway

For proxy integrations the function must return { statusCode, body } with body as a string; check logs for exceptions.

sam local fails: Docker not running

Start Docker Desktop/Engine; SAM runs functions in containers locally.

Slow first request (cold start)

Keep bundles small, use arm64, avoid heavy init, or enable provisioned concurrency for latency-critical paths.

Best practices

  • One function per job; keep handlers small and stateless.
  • Create clients outside the handler to reuse connections.
  • Least-privilege execution roles; secrets from SSM/Secrets Manager.
  • Set timeouts, memory and alarms deliberately.
  • Use RDS Proxy or DynamoDB to avoid database connection storms.