aws-lambda Cannot find module
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
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.
Related reading
- AWS - Accessing instances in private subnet using EIP
- AWS - Disconnected No supported authentication methods available server sent publickey
- AWS - Give readonly permissions for all services
- AWS - One of the required keys was not given a value
- AWS - SQS Batch Size and Lambda approach
- AWS - SSL/HTTPS on load balancer
- AWS - subscribe multiple lambda logs to one elasticsearch service
- AWS - What are the exact differences between EC2, Beanstalk and LightSail?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.