Serverless - Lambda Layers "Cannot find module 'request'"

Mikerizzo picture Mikerizzo · Apr 5, 2019 · Viewed 9.6k times · Source

When I deploy my serverless api using:

serverless deploy

The lambda layer gets created but when I go to run the function is gives me this error:

"Cannot find module 'request'"

But if I upload the .zip file manually through the console (the exactly same file thats uploaded when I deploy), it works fine.

Any one have any idea why this is happening?

environment:
SLS_DEBUG: "*"

provider:
name: aws
runtime: nodejs8.10
stage: ${opt:api-type, 'uat'}-${opt:api, 'payment'}
region: ca-central-1
timeout: 30
memorySize: 128
role: ${file(config/prod.env.json):ROLE}
vpc:
    securityGroupIds:
    - ${file(config/prod.env.json):SECURITY_GROUP}
    subnetIds:
    - ${file(config/prod.env.json):SUBNET}
apiGateway:
    apiKeySourceType: HEADER
apiKeys:
    - ${file(config/${opt:api-type, 'uat'}.env.json):${opt:api, "payment"}-APIKEY}

functions:
- '${file(src/handlers/${opt:api, "payment"}.serverless.yml)}'

package:
# individually: true
exclude:
    - node_modules/**
    - nodejs/**

plugins:
- serverless-offline
- serverless-plugin-warmup
- serverless-content-encoding

custom:
contentEncoding:
    minimumCompressionSize: 0 # Minimum body size required for compression in bytes

layers:
nodejs:
    package:
    artifact: nodejs.zip
    compatibleRuntimes:
    - nodejs8.10
    allowedAccounts:
    - "*"

Thats what my serverless yaml script looks like.

Answer

Elon Zito picture Elon Zito · Jan 25, 2020

Make sure you run npm install inside your layers before deploying, ie:

cd ~/repos/repo-name/layers/utilityLayer/nodejs && npm install

Otherwise your layers will get deployed without a node_modules folder. You can download the .zip of your layer from the Lambda UI to confirm the contents of that layer.