This sample demonstrates AWS Lambda Layers using the Serverless Framework with LocalStack.
Lambda Layers allow you to share code and libraries across multiple Lambda functions without bundling them into each function's deployment package.
This sample:
- Creates a Lambda Layer containing a shared utility library (
lib.js) - Creates a Lambda function that imports and uses the layer
- The layer is extracted to
/opt/nodejs/at runtime
┌─────────────────────────────────────────┐
│ Lambda Function │
│ │
│ const { echo } = require('/opt/...') │
│ │
└────────────────────┬────────────────────┘
│ uses
▼
┌─────────────────────────────────────────┐
│ Lambda Layer │
│ │
│ /opt/nodejs/lib.js │
│ └── echo(message) │
│ │
└─────────────────────────────────────────┘
- LocalStack Pro running (
localstack start) - Node.js 18+
- npm
# Deploy
./scripts/deploy.sh
# Test
./scripts/test.sh| File | Description |
|---|---|
handler.js |
Lambda function that uses the layer |
layer/nodejs/lib.js |
Shared library (packaged as layer) |
serverless.yml |
Serverless Framework configuration |
scripts/deploy.sh |
Deployment script |
scripts/test.sh |
Test script with validation |
Lambda layers for Node.js must follow this structure:
layer/
└── nodejs/
└── lib.js # Extracted to /opt/nodejs/lib.js at runtime
The test script validates:
- Lambda function is active
- Layer is attached to function
- Function invocation succeeds (returns 200)
- Response body contains expected message
- No import/module errors (layer loaded correctly)
- AWS Lambda
- Lambda Layers
- API Gateway (HTTP endpoint)
- S3 (deployment bucket)