Import npm Modules into AWS Lambda Function


Welcome to “Continuous Improvement,” the podcast where we explore the world of software development and discuss ways to enhance our skills. I’m your host, Victor, and in today’s episode, we’ll be diving into the topic of deploying Node.js Lambda functions on Amazon Web Services (AWS).

Have you ever found yourself in a situation where you wanted to import a third-party library, like lodash, into your Node.js Lambda function on AWS? In today’s blog post, we learned that the online editor on AWS doesn’t provide a straightforward way to achieve this. But fear not! There’s a workaround that I’d like to share with you.

The first step is to create a folder on your local machine and copy the index.js file into it. Once that’s done, open up your terminal and navigate to the folder you just created.

In the terminal, run npm init . This command initializes your project and generates a package.json file. This file will keep track of all the dependencies required for your Lambda function.

Next, we need to install the third-party library, in this case, lodash. Run npm install lodash --save in the terminal. This will add lodash as a dependency and update the package.json file accordingly.

Now that we have the library installed, let’s use it in our index.js file. Add the following line of code at the beginning of the file:

    let _ = require('lodash');

With lodash successfully imported into our Lambda function, it’s time to prepare for deployment. To do this, we need to zip the entire folder, including the node_modules directory. In the terminal, use the zip -r function.zip . command to accomplish this.

The final step is to deploy the zip file to AWS using the AWS CLI tool. In your terminal, type aws lambda update-function-code --function-name yourFunctionName --zip-file fileb://function.zip. Here, make sure to replace yourFunctionName with the actual name of your function.

If everything goes smoothly, the deployment should be successful, and you’ll see a confirmation message in the terminal, indicating that the update was completed.

That’s it! You’ve now learned how to deploy a Node.js Lambda function with third-party dependencies on AWS. Remember, continuous improvement is essential in the ever-evolving world of software development.

Thank you for joining me on this episode of “Continuous Improvement.” I hope you found the information helpful. If you have any questions or suggestions, feel free to reach out. Don’t forget to subscribe to our podcast for more exciting topics and stay tuned for the next episode.