How do I resolve "Unable to import module" error that I receive when I run Lambda code in Node.js?

Last updated: 2021-07-26

I receive the "Unable to import module" error when I try to run my AWS Lambda code in Node.js.

Short description

You typically receive this error when your Lambda environment can't find the specified library in the Node.js code. This is because Lambda isn't prepackaged with all Node.js libraries.

To resolve this error, create a deployment package or Lambda layer that includes the libraries that you want to use in your Node.js code for Lambda.

Note: The following steps show you how to create a Lambda layer rather than a deployment package. This is because you can reuse the Lambda layer across multiple Lambda functions. Each Lambda runtime adds specific /opt directory folders to the PATH variable. If the layer uses the same folder structure, your Lambda function's code can access the layer content without specifying the path.

Important: Put the library that you import for Node.js inside the nodejs/node_modules folder.

Resolution

It's a best practice to create a Lambda layer on the same operating system that your Lambda runtime is based on. For example, all versions of Node.js are based on the Amazon Linux 2 Amazon Machine Images (AMI).

To create a Lambda layer for a Node.js library:

1.    Create an Amazon Elastic Compute Cloud (Amazon EC2) instance from an Amazon Linux 2 AMI.

2.    Create an AWS Identity and Access Management (IAM) role with permissions to call the publish-layer-version API. Then, attach the IAM role to the EC2 instance.

Note: Your EC2 instance now has permissions to upload Lambda layers for the publish-layer-version API call.

3.    Connect to your EC2 instance, and then install Node.js:

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
$ . ~/.nvm/nvm.sh
$ nvm install node

4.    Create a nodejs folder:

$ mkdir nodejs

5.    Install the aws-xray-sdk library into the nodejs folder:

$ cd nodejs
$ npm init  ***answer all queries regarding initialization that create a package.json file***
$ npm install --save aws-xray-sdk

Note: Replace the aws-xray-sdk example library with the Node.js library that you want to import.

6.    Create a zip archive for the aws-xray-sdk library:

$ zip -r layer.zip nodejs

Note: The aws-xray-sdk library is in the required folder format for a Node.js layer: nodejs/node_modules.

7.    Publish the Lambda layer:

$ aws lambda publish-layer-version --layer-name xray --zip-file fileb://layer.zip --compatible-runtimes nodejs12.x --region us-east-1