aws-lambda Cannot find module
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Lambda is AWS's way of letting you run code without worrying about servers. But if you’ve ever encountered a situation where AWS Lambda complains with “Cannot find module”, you know how frustrating it can be. This problem is common, but with a little understanding, it can be solved efficiently. In this article, we will walk through the reasons why this error might occur in an AWS Lambda environment, and how to resolve it.
Common Reasons for "Cannot find module" Error
The "Cannot find module" error typically occurs when AWS Lambda is unable to locate the module specified in your code. Here are some common reasons:
- Incorrect File Path: The most frequent reason is an incorrect file-path reference in your `require()` or `import` statement due to the structure of your deployed package.
- Packaging Errors: Failing to include dependencies or building the package incorrectly can lead to a situation where the function cannot locate the modules it needs.
- Case Sensitivity: AWS Lambda runs on a Linux-based environment, which is case-sensitive. A mismatch in module naming due to letter casing will lead to this error.
- Node.js Version Mismatch: Utilizing Node.js features not supported by the version running in AWS Lambda may cause modules to not be found.
- Third-party Library Issues: Sometimes the problem stems from incorrect or missing dependencies you retrieve from third-party sources like npm.
- Incorrect Lambda Handler: The handler string in your Lambda configuration does not correctly reference your module paths.
Investigating and Solving the Error
1. Correct File Path
Always ensure that paths used in require statements match the actual directory structure:
- Run `npm install` before deploying to make sure that all dependencies are included.
- Consider running `npm prune --production` to reduce the package size by eliminating unnecessary files before deploying.

