AWS
AWS Lambda
Lambda Error
Cannot Find Module
Serverless Computing

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.

Practice system design

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:

  1. 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.
  2. 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.
  3. 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.
  4. Node.js Version Mismatch: Utilizing Node.js features not supported by the version running in AWS Lambda may cause modules to not be found.
  5. Third-party Library Issues: Sometimes the problem stems from incorrect or missing dependencies you retrieve from third-party sources like npm.
  6. 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
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track 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.

Practice system design