Cannot find module error when site is live and function is invoked

I keep getting this error and I don’t know why:
// https://nps-alert-tracker.netlify.com/.netlify/functions/token-hider?stateName=CA

{
“errorMessage”: “Cannot find module ‘node-fetch’”,
“errorType”: “Error”,
“stackTrace”: [
“Module.require (module.js:596:17)”,
“require (internal/module.js:11:18)”,
“Object. (/var/task/token-hider.js:2:15)”,
“Module._compile (module.js:652:30)”,
“Object.Module._extensions…js (module.js:663:10)”,
“Module.load (module.js:565:32)”,
“tryModuleLoad (module.js:505:12)”,
“Function.Module._load (module.js:497:3)”
]
}

if someone could help me out that would be amazing, because I feel like i’ve tried everything.

Bundle up the modules with your functions, if those dependencies are not included in node already. In this case, you will have to bundle node-fetch with your function.

There will need to be an existing module for your bundle. There is 2 ways you can do this within a project:

  • Bring the node_modules dependencies with you from the function directory or
  • Pre-build your modules with a bundler (like webpack) into your script and target a node build

These might seem like a lot of work, but in most cases it is simpler than it seems.

@philhawksworth shows an example in a starter repository of a function that uses the first method above by npm install using a local package.json config for node-fetch here. Then the results are stored into the repository, so Netlify can pick them up when creating the functions. There is no pre-build needed.

The second option would use the same method as this repository where your functions exist in a source location and are bundled to a distribution location using the netlify-lambda cli.

Note: Think of each function directory as a self contained script that will be running in its own node instance without any node modules install. The function needs all dependencies installed into its directory prior to being deployed. Both of the cases above meet this requirement.

3 Likes