Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

133
Views
Module not found for lambda layer (AWS, JavaScript)

I have a serverless application that uses CDK. I want to add a lambda layer to share some functionality across different areas of the application.

I define the layer in a CDK stack using

const encryptLayer = new lambda.LayerVersion(this, 'encrypt-layer', {
  compatibleRuntimes: [
    lambda.Runtime.NODEJS_14_X,
  ],
  code: lambda.Code.fromAsset(path.join(__dirname,'src/Layers/EncryptDecryptFunctions')),
  description: 'shared functions to encrypt/decrypt data using asymmetric key'
});

and I added encryptLayer to a few of the functions in the same stack using the layers attribute when calling new lambda.Function().... I deployed this and I see the layer sitting under the correct function in the console.

The file structure for the layer is

src
   Layers
      EncryptFunctions
         nodejs
            encrypt.js
            package.json

and I am trying to import it using const { encrypt } = require("/opt/nodejs/encrypt") per the AWS documentation. However, I am getting a module not found exception when running the lambda that uses the encrypt method.

Is there anything else I need to do so that I can use the layer's code in my lambdas? For both code in the same repository and in a different repository?

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

This seems an issue of PATH. As shown in this doc, paths for each Lambda runtime of Node.js are:

  • nodejs/node_modules
  • nodejs/node14/node_modules (NODE_PATH)

Therefore, you can add node_modules/ direcitory. Use nodejs/node_modules/ instead of nodejs in the file structure.

And import in lambda code will be like:

const encrypt = require('encrypt')
7 months ago · Juan Pablo Isaza Report

0

The issue here is that I was bundling my lambdas using webpack and I didn't add '/opt/nodejs/encrypt' to my externals in webpack config. Doing that fixed my problem.

7 months ago · Juan Pablo Isaza Report

0

You can use a serverless framework where you can define all in yml file like the below code.

layers:
  AnalyticsShared:
    path: node_modules
    name: analytics-shared-${opt:stage, self:provider.stage}
    description: "Shared node modules for analytics"


functions:
  track:
    handler: analytics.queue
    timeout: 30
    layers:
      - {Ref: AnalyticsSharedLambdaLayer}

Ref URLs: https://www.serverless.com/framework/docs/providers/aws/guide/layers

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.