shou2017.com
JP

Create AWS Lambda layer with serverless framework (node.js)

Sat May 9, 2020
Sat Aug 10, 2024
AWS

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.

Environment

  • macOS Catalina
    • 10.15.4
  • serverless framework
    • Framework Core: 1.67.3 (standalone)
    • Plugin: 3.6.6
    • SDK: 2.3.0
  • node.js
    • v12.15.0
  • aws
    • aws-cli/1.18.0 Python/3.7.3 Darwin/19.4.0 botocore/1.15.0

Create a service using serverless framework

Since it’s node.js, use the aws-nodejs template.

% sls create --template aws-nodejs --path sls-layer

Install npm packages

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

Configure 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.

AWS Lambdaのlayerをserverless frameworkでつくる(node.js)

On the function code side, the node_modules, package.json, and other files are gone, making it neat and clean.

AWS Lambdaのlayerをserverless frameworkでつくる(node.js)

See Also