When developing Lambda with node.js
, npm packages
are essential.
However, if every Lambda function has its own node_modules
, it becomes heavy. As a result, you can’t see the Lambda code from the console!
What should you do? After searching, I found AWS Lambda Layers. By using this, you can upload libraries as a Layer and have your Lambdas use the uploaded Layer.
Layers can be used from the console, but in real development, you rarely use the console. So this time, I’ll make a note of the method using the serverless framework, which I often use.
Since it’s node.js, use the aws-nodejs template.
% sls create --template aws-nodejs --path sls-layer
Create a layer
folder directly under the directory. The structure looks like this:
├── handler.js
├── my-layer ← Directory to store the layer
│ └── nodejs
│
└── serverless.yml
Move to the nodejs
folder. Install the npm package. Here, I’ll use hello-world-npm as an example.
nodejs% npm init -y
nodejs% npm i hello-world-npm
After completing these steps, the folder structure should look like this:
├── handler.js
├── my-layer ← Directory to store the layer
│ └── nodejs
│ └── node_modules
│ └── package-lock.json
│ └── package.json
│
│
└── serverless.yml
service: sls-layer
provider:
name: aws
runtime: nodejs12.x
functions:
hello:
handler: handler.hello
layers:
- {Ref: MylayerLambdaLayer}
layers:
mylayer:
path: my-layer
The configuration is relatively simple. You just use the built-in function Ref to return the specified parameter or resource.
After that, you just need to call hello-world-npm in your Lambda function.
'use strict';
const helloWorld = require('hello-world-npm')
module.exports.hello = async event => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: helloWorld(),
input: event,
},
null,
2
),
};
};
That’s it. Just to make sure everything works, I checked it, and it works fine.
% sls invoke -f hello
{
"statusCode": 200,
"body": "{\n \"message\": \"Hello World NPM\",\n \"input\": {}\n}"
}
I also checked on the AWS Console.
The layers are added correctly.
On the function code side, the node_modules
, package.json
, and other files are gone, making it neat and clean.