How To Add NodeJs Library Dependencies in a AWS Lambda Layer with Serverless Framework
AWS announced neat Lambda Layers feature at re:Invent 2018, which gives developers up to five packages to inject into a given function at runtime. This promotes component sharing and keeps the core function package as small as possible.
Use Case
In this example, I move nodeJs runtime dependencies out of lambda function code by placing them in a layer.
To get started, update to v1.34.0 or greater for layers support and create a serverless project:
$ npm i -g serverless$ serverless create --template aws-nodejs --path myTestLayer
To include libraries in a layer, place them in layer/nodejs/node_modules, please NOTE that the nodejs directory name is not random and must be nodejs.
Reference
I m now adding lodash and moment dependencies to layer as following:
$ cd myTestLayer$ mkdir -p layer/nodejs$ cd layer/nodejs$ npm install --save lodash moment
Next, add the layers config to serverless.yml to define your layer that will contain nodejs libraries. The path property is a path to a directory that will be published as your layer:
layers:
commonLibs:
path: layer
compatibleRuntimes:
- nodejs8.10
Then add your function in serverless.yml, specify that your function uses the layer you’re publishing:
functions:
hello:
handler: handler.hello
layers:
# Ref name is generated by TitleCasing the layer name & appending LambdaLayer
- {Ref: CommonLibsLambdaLayer}
The serverless.yml should now look like:
service: myTestLayerprovider:
name: aws
runtime: nodejs8.10
region: ap-southeast-2functions:
hello:
handler: handler.hello
layers:
# Ref name is generated by TitleCasing the layer name & appending LambdaLayer
- {Ref: CommonLibsLambdaLayer}layers:
commonLibs:
path: layer
compatibleRuntimes:
- nodejs8.10
Now, We need to write our handler. The lambda function is a Calculator: Add or Subtract Number of Days to a Today’s Date, Replace the contents of handler.js with the following code:
"use strict";const _ = require("lodash");
const moment = require("moment");module.exports.hello = async (event, context, callback) => {
const curried = _.curry(calculateDate);
callback(null, curried(moment().format())(event));
};const calculateDate = (datetime, days)=> {
return moment()
.add(days, "days")
.format("Do MMMM YYYY, h:mm:ss a");
};
Deploy both the layer & updated function with following
$ serverless deploy
Let’s test it out by following command line:
#data is days you want to Add or Subtract to today's date
$ serverless invoke --function hello --data=2
That’s all bout it! You now get the date calculated!
For the full source of this example, check it out here.
AWS Lambda Runtimes
You can now select a custom runtime when creating or updating a function. With this selection, the function must include (in its code or in a layer) an executable file called bootstrap, responsible for the communication between your code (that can use any programming language) and the Lambda environment.