NodeJS
AWS Lambda
aws-sdk
error handling
module not found

Error Cannot find module 'aws-sdk' in NodeJS AWS Lambda Function

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Encountering the error `Error: Cannot find module 'aws-sdk'` in a NodeJS AWS Lambda function can be frustrating. AWS Lambda, a serverless compute service, allows you to run code without managing servers, making your infrastructure automatic and scalable. However, understanding how to manage dependencies, like the AWS SDK, is crucial for smooth operation. This article details why this error occurs, how to resolve it, and additional best practices for managing NodeJS dependencies in AWS Lambda.

Understanding the Error

AWS Lambda functions run in a specific execution environment. By default, AWS SDK for JavaScript is included with the Node.js Lambda runtime in the AWS Lambda execution environment. If you're encountering the error that the module cannot be found, this may be due to several reasons:

  1. Local Environment Mismatch: When running tests locally using older SDK or different Node.js versions.
  2. Custom Deployment Package: Creating a deployment package locally and not including AWS SDK.
  3. Resolved Errors in Other Environments: Some other issue might have given rise to this error indirectly.
  4. Lambda Layer Configuration: If layers are not updated or correctly specified for functions that expect an SDK version not provided by default.

Possible Solutions

Here are the steps to resolve the error:

1. Check Lambda Runtime

Ensure that you are using a supported version of Node.js that includes the required AWS SDK version. AWS Lambda often updates its SDK, so make sure your function is compatible with the latest environment.

2. Package Your Dependencies

If you need a specific version of `aws-sdk` or you need it to be bundled with other dependencies:

  • Local Packaging: Install aws-sdk locally within your project using npm, and upload with your function code.
    Example:
  • Create a Layer: Include `aws-sdk` in a layer to keep your function clean and deployment size small.
  • Attach the Layer to Your Function: Use the AWS Console or CLI to attach this layer to your Lambda function.
  • Ensure all code and resources point to the desired SDK version.
  • Validate if the `package.json` reflects dependencies correctly.

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

All Rights Reserved.