Easy-Peazy Node Dependencies in AWS Lambda Using Layers
Tags: aws, lambda, dependencies, javascript
Published: 2021-01-31 14:37:19

---
title: Easy-Peazy Node Dependencies in AWS Lambda Using Layers
published: true
description: Getting a "Cannot find module" error in an AWS lambda? Want to run npm install for your node_modules in a serverless function? Keep the accessible lambda code editor open and skip zipping up your entire handler by using AWS Lambda Layers
tags: aws, lambda, dependencies, javascript
---

Do `"Cannot find module Runtime.ImportModuleError"` errors have you down?

I honestly thought one of the big selling points of AWS Lambdas were that they were super fast to spin up. But what is a NodeJs method without some npm/yarn dependencies? Kidding, but I was disappointed to find out that there wasn't an easy way to run `npm install` and keep editing my handler function in the AWS Lambda code editor.

There is a way: _**layers**_. Using <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html" target="_blank">layers</a> in Lambda functions allows for importing NodeJs dependencies via the AWS code editor UI. These are the steps:
1. <a href="#1-compress-dependencies">Compress Dependencies</a>
1. <a href="#2-create-a-layer">Create a Layer</a>
1. <a href="#3-attach-layer-amp-deploy-lambda">Attach Layer & Deploy Lambda</a>

---  
  
## 1. Compress Dependencies

The goal of this step is to end up with a zipped archive of the node_modules folder with just the dependencies you'll need for your lambda.

Start by creating an empty directory named `nodejs` and then run `npm init` inside of it by running these commands line-by-line:

```bash
mkdir nodejs

cd nodejs

touch index.js

npm init -y
```

Once you have the directory, install dependencies that your Lambda will need using `npm i --save ...` (I'm using `haikunator` as an example):

```bash
npm i --save haikunator
```

Then require/export the dependencies in the main file of your project. Do this by writing `exports.exampleDependency = require('example-dependency')` for each dependency you have in the project.

You can just write the export statement in the index.js file directly, or run the below statement via CLI (of course substituting `haikunator` for your own dependency).

```bash
cat > index.js
exports.haikunator = require('haikunator');
```

Final index.js file:
```javascript
exports.haikunator = require('haikunator ');
```

That's the hard part! Now you need to zip up the folder with index.js/ package.json/ node_modules. This is what your directory structure should look like before it is zipped up:

<img src="https://dev-to-uploads.s3.amazonaws.com/i/qjlv41o47wni3nm50rv8.PNG" alt="Index, package.json and node_modules in a folder" width="300" style="margin-bottom: 25px;" />

---  
  
## 2. Create a Layer

Once you've zipped the files, go to Lambda > Layers in the AWS UI. Create a new layer (independent of your Lambda function - that part comes later) named whatever you want with `Node.js` as the compatible runtime. Upload your `nodejs.zip` archive as the layer code.

<img src="https://dev-to-uploads.s3.amazonaws.com/i/okbaba320d9qd44eislq.PNG" alt="Creating a layer in AWS UI" width="100%" style="margin-bottom: 25px;" />

---  
  
## 3. Attach Layer & Deploy Lambda 

This is the last step and is the part that links the dependencies to your Lambda. Either create a new Lambda function or navigate to an existing one. Click on _*"layers"*_ in the designer section of the UI and go to _*"Add a Layer."*_

<img src="https://dev-to-uploads.s3.amazonaws.com/i/3txn9pm0rw8mr8zhl14t.PNG" alt="Editing layers for your Lambda" style="margin-bottom: 25px;" width="100%" />

The Add Layer screen will show something like the below. Choose _*Custom Layers*_ and the layer created in the previous step (the one where `nodejs.zip` was uploaded) will appear in the dropdown. Click "add" and you're good to go!

![Add your created layer to your Lambda handler](https://dev-to-uploads.s3.amazonaws.com/i/xnnth6iswkawj4p4pm3k.PNG)

Now the npm/yarn dependencies are available to use in the Lambda code editor.

> __**Quick tip:**__ if you followed the steps and named the zip file as directed, dependencies can be accessed via `require('dependencyName')`.
> Otherwise, access your dependencies via the `/opt/nameOfZip` path. For example: if you uploaded myDir.zip, use `require('/opt/myDir')`).

Here is my example code living in the Lambda function:

```js
const haikunator = require('haikunator');
// if layer has custom zip name use the below
// const { haikunator } = require('/opt/nodejs');

const handler = async (event) => {

    const h = new haikunator();
    const response = {
        statusCode: 200,
        body: h.haikunate({
            tokenLength: 0,
            delimiter: '-'
        })
    };
    return response;
};

exports.handler = handler;
```

That's it! Update Press the _*Deploy*_ button to your heart's content and update code in the AWS editor. Happy layering!