Home > front end >  Module not found for lambda layer (AWS, JavaScript)
Module not found for lambda layer (AWS, JavaScript)

Time:10-22

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?

CodePudding user response:

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/, like nodejs/node_modules/ instead of nodejs.

And import in lambda code will be like:

const encrypt = require('encrypt')

CodePudding user response:

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

  • Related