patternjavascriptTip
AWS SAM local development and deployment for serverless applications
Viewed 0 times
AWS SAM CLI 1.x
SAM CLIsam locallocal lambdasam buildserverless application modelsam deployesbuildlocal API Gateway
aws-lambda
Problem
Developing Lambda functions by deploying to AWS on every code change is slow. Testing event-handling logic requires constructing synthetic test events manually.
Solution
Use AWS SAM CLI for local Lambda invocation, API Gateway emulation, and DynamoDB local. Run
sam local invoke for single invocations or sam local start-api for local HTTP server. Use sam build with esbuild for TypeScript transpilation.# template.yaml
Globals:
Function:
Runtime: nodejs20.x
Architectures: [arm64]
Environment:
Variables:
TABLE_NAME: !Ref AppTable
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handler.handler
Events:
Api:
Type: HttpApi
Properties:
Path: /items
Method: GETWhy
SAM CLI runs Lambda functions in a Docker container matching the actual Lambda runtime environment. This catches runtime-specific bugs (native modules, path differences) before deployment. SAM is also a lighter-weight alternative to CDK for small serverless projects.
Gotchas
- sam local does not perfectly emulate all AWS services — DynamoDB, S3 calls still go to real AWS unless you use localstack
- SAM uses CloudFormation under the hood — it deploys through a CloudFormation stack and has the same limitations
- sam build with esbuild requires @aws-sdk packages to be marked as external (they are bundled in the Lambda runtime)
- Hot reloading is not built into SAM — use nodemon or ts-node-dev externally and restart the SAM process
- SAM Accelerate (sam sync) enables incremental deployments that sync only changed functions — much faster than full deploy
Code Snippets
SAM CLI workflow for local development and deployment
# Build TypeScript Lambda with esbuild
sam build --use-container
# Invoke locally with a test event
sam local invoke MyFunction --event events/api-event.json
# Start local API Gateway
sam local start-api --port 3000
# Deploy to AWS
sam deploy --guidedContext
Local development and deployment of serverless Lambda applications
Revisions (0)
No revisions yet.