AWS Lambda Serverless – Packaging nodejs modules to a layer

If you have used serverless framework for AWS Lambda with Python, then it is quite possible that you would have used the serverless-python-requirements plugin to migrate the libraries (numpy, pandas, etc.) to a layer. It is desirable to do the same with node js as well. Here are the steps to do the same:

  1. Navigate to your project folder containing the serverless.yml file
  2. Create a new folder named layer (you can name it something else as well, if you wish)
  3. Within this folder, create a new folder called nodejs (this should be named exactly nodejs)
  4. Within this folder, install all the modules you require in the project (using npm install)
  5. This will create a node_modules folder within the nodejs folder, and a package-lock.json file
  6. Now, your layer is ready. Next, open your serverless.yml file, and add the following lines:
layers:
  myLibs:
    path: layer //Replace with name of your folder
    compatibleRuntimes:
      - nodejs8.10 //Replace with your nodejs runtime

Include the layer for every function that requires these modules:

functions:
  hello:
    handler: handler.hello
    layers:
        # Ref name is generated by TitleCasing the layer name & appending LambdaLayer
      - {Ref: MyLibsLambdaLayer}

That’s it. Now, on deploying this service, you will see the layer created for your function in the AWS Lambda console. You shall also be able to visualize the code in the editor (since the node_modules are now sitting in the layer, away from your application code), and not get that annoying message:

deployment package of your Lambda function is too large to enable inline code


I hope you liked this article. For more tutorials on AWS, check out https://iotespresso.com/category/aws/. Also, if you are planning to become a certified AWS Solutions Architect, I’d recommend that you check out this course on Udemy. I took this course and found the lectures to be lucid, to-the-point, and fun. I hope they will help you as well.

2 comments

  1. Can you please share your full serverless.yml? I’m am trying this, and it works, however the “node_modules” at the root of the project continues to be included in the main zip file…

Leave a comment

Your email address will not be published.