Unable to locate module 'puppeteer'

I am working with AWS Lambda using Node.js and trying to import the module from an absolute directory path (/opt/nodejs/node_modules/puppeteer). Everything functions correctly on my local machine, but once the code is bundled with Webpack/serverless-webpack and deployed to AWS Lambda, executing require(‘puppeteer’) generates the following error:

{“errorMessage”:“Unable to locate module ‘puppeteer’”,“errorType”:“Error”,“stackTrace”:[“webpackMissingModule (/var/task/src/render/handler.js:643:89)”,“/var/task/src/render/handler.js:643:173”,“next (native)”,“step (/var/task/src/render/handler.js:608:191)”,“/var/task/src/render/handler.js:608:361”]}

I’ve verified that:

  • The AWS Lambda Layer is correctly mounted at /opt.
  • The directory /opt/nodejs/node_modules/puppeteer is present.
  • The environment variable NODE_PATH correctly references /opt/nodejs/node_modules.

To resolve the issue of AWS Lambda being unable to locate your Puppeteer module, there are several strategies you might consider:

Firstly, ensure that Puppeteer is included in your node_modules directory when you package your Lambda function. Given that you are using webpack, it's crucial that your bundling configuration isn't excluding Puppeteer. You can achieve this by ensuring Puppeteer is listed as a dependency in your package.json.

1. Webpack Configuration:

Check if Puppeteer is incorrectly set as an externals in your Webpack configuration. Puppeteer should be bundled with your deployment package. Here's an example configuration:

module.exports = { // other webpack configurations externals: [], // Ensure Puppeteer is not listed here };

2. AWS Lambda Layer:

When using Lambda Layers, make sure you have followed these steps:

  • Double-check that the layer containing Puppeteer is attached to your Lambda function.
  • Confirm that the directory structure in your layer allows Node.js to recognize the path, since case sensitivity can often lead to issues.
  • Update your lambda handler’s context so it’s aware of the NODE_PATH environment variable, ensuring it points to /opt/nodejs/node_modules.

3. Use of Headless Chrome binaries:

Note that Puppeteer requires Chromium binaries to function. Ensure the necessary files are available and that any initialization scripts correctly reference them.

When you deploy your function with Serverless Framework or another deployment tool, verify each step in the process to ensure that dependencies are correctly packaged and uploaded. Sometimes manually adding Puppeteer in a mock deployment environment can expose where things go wrong.

Hey Emma, make sure Puppeteer isn’t excluded in your Webpack config. Check your Webpack setup:

module.exports = {
  externals: [], // Puppeteer should not be here
};

Verify the AWS Lambda layer containing Puppeteer is attached and set your NODE_PATH to /opt/nodejs/node_modules. Ensure Chromium binaries are accessible too.

Happy coding!