Search code examples
aws-lambdaserverless-framework

Cannot find module 'handler' when running simple lambda deployed by serverless


I am trying to start learning serverless / lambda so I created a simple lambda and deployed it with serverless which worked.

However when I want to test the endpoint of the lampbda I get a 502 back. When I look in the logs it tells me that it can not find the module handler which does not make any sense...

here is the log:

{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'handler'\nRequire stack:\n- 
/var/runtime/UserFunction.js\n- /var/runtime/index.js",
 "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'handler'",
"Require stack:",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
"    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
"    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
"    at Object.<anonymous> (/var/runtime/index.js:43:30)",
"    at Module._compile (internal/modules/cjs/loader.js:1158:30)",
"    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)",
"    at Module.load (internal/modules/cjs/loader.js:1002:32)",
"    at Function.Module._load (internal/modules/cjs/loader.js:901:14)",
"    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)",
"    at internal/main/run_main_module.js:18:47"
]
}

Solution

  • This normally means that it can not find the method that is the starting point to execute.

    For example on your serverless.yml you can have something like this

    functions:
      getUsers:
        handler: userFile.handler
    

    this would mean that it's required to have a userFile in the same folder of the serverless.yml with the method handler exported.

    module.exports.hello = async event => {
      return {
        statusCode: 200,
        body: JSON.stringify(
          {
            message: 'Go Serverless v1.0! Your function executed successfully!',
            input: event,
          },
          null,
          2
        ),
      };
    };
    

    Note that it does not need to be named handler function, just needs to have the same name defined on the serverless.yml