AWS Lambda Layers - Node Modules not working

Hi all,

I am trying to use AWS Lambda Layers to make the node_modules folder a common layer as I have multiple functions that rely on it.

I have successfully created a layer and linked the layer to a function, however when I invoke it, it gives me an error that a module (in node modules) that it tried to require does not exist. Which means the layer isn’t working or somehow the function can’t find the right path.

I checked the layer by downloading and all my modules are there. I also checked the function and it has the layer assigned to it.

Here my yml file sections:

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}

What am I doing wrong? Can someone please help me.

1 Like

Do you need to provide compatibleRuntimes? Or when referencing the node_modules now, are you going through /opt/layerName/node_modules?

You need to insert your node_modules directory into nodejs directory
└ nodejs/node_modules
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path

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}

This way of writing is correct.“AnalyticsShared:
This part doesn’t always work correctly though Serverless Framework says as following in AWS - Layers:Using your layers.

To use a layer with a function in the same service, use a CloudFormation Ref. The name of your layer in the CloudFormation template will be your layer name TitleCased (without spaces) and have LambdaLayer appended to the end. EG:

  • wrong
layers:
  test:
    path: layer
functions:
  hello:
    handler: handler.hello
    layers:
      - { Ref: TestLambdaLayer }
  • right
layers:
  Test:
    path: layer
functions:
  hello:
    handler: handler.hello
    layers:
      - { Ref: TestLambdaLayer }

This phenomenon may happen when layers name is equal to service name. That’s because layers name create zip file (e.g.Test.zip) as well as service name create zip file (e.g.test.zip) when sls deploy with cloudformation info.

Hi…At the point when you make a layer, you should package all it’s anything but a .compress record document. You transfer the .compress record file to your layer from Amazon Simple Storage Service (Amazon S3) or your neighborhood machine. Lambda separates the layer substance into the/pick registry when setting up the execution climate for the capacity.