Netlify Functions Can't find module

I’m having issues with my serverless functions, and am at a loss. They work locally with Netlify dev, but not when they’re deployed. My site is preston-lamb-consulting.netlify.app.

I have read a dozen posts here on the community and elsewhere about getting the functions working. They were working up until I deployed my new Scully based site this week (was jekyll before). The functions are in the .netlify/functions folder, and the package.json is on the root of the project. The build log shows that the functions are packaged and deployed properly, but when I hit the endpoint, I get an error that node-fetch can’t be found.

Again, I have the package declared in the root package.json, and it works locally. I’m at a loss as to what I should try next.

Function error log:

7:30:09 PM: 2020-12-04T02:30:09.729Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/src/download-stats-npm.js\n- /var/task/download-stats-npm.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'","Require stack:","- /var/task/src/download-stats-npm.js","- /var/task/download-stats-npm.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:1015:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)","    at Module.load (internal/modules/cjs/loader.js:879:32)","    at Function.Module._load (internal/modules/cjs/loader.js:724:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
7:30:10 PM: 2020-12-04T02:30:10.076Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/src/download-stats-npm.js\n- /var/task/download-stats-npm.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'","Require stack:","- /var/task/src/download-stats-npm.js","- /var/task/download-stats-npm.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:1015:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)","    at Module.load (internal/modules/cjs/loader.js:879:32)","    at Function.Module._load (internal/modules/cjs/loader.js:724:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
7:30:10 PM: Duration: 234.03 ms	Memory Usage: 14 MB	
7:30:10 PM: Unknown application error occurredRuntime.ImportModuleError
7:30:11 PM: 2020-12-04T02:30:11.100Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/src/download-stats-npm.js\n- /var/task/download-stats-npm.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'","Require stack:","- /var/task/src/download-stats-npm.js","- /var/task/download-stats-npm.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:1015:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)","    at Module.load (internal/modules/cjs/loader.js:879:32)","    at Function.Module._load (internal/modules/cjs/loader.js:724:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}

hmm, interesting. can you paste your package.json please?

I wonder whether node-fetch is getting installed correctly.

{
	"name": "personal-site",
	"version": "0.0.0",
	"scripts": {
		"ng": "ng",
		"start": "ng serve",
		"build": "ng build",
		"build:prod": "ng build --prod",
		"test": "ng test",
		"lint": "ng lint",
		"e2e": "ng e2e",
		"scully": "scully",
		"scully:serve": "scully serve",
		"netlify": "npm run build:prod && npm run scully"
	},
	"private": true,
	"dependencies": {
		"@angular/animations": "~10.0.8",
		"@angular/common": "~10.0.8",
		"@angular/compiler": "~10.0.8",
		"@angular/core": "~10.0.8",
		"@angular/forms": "~10.0.8",
		"@angular/platform-browser": "~10.0.8",
		"@angular/platform-browser-dynamic": "~10.0.8",
		"@angular/router": "~10.0.8",
		"@gammastream/scully-plugin-sitemap": "^1.0.4",
		"@scullyio/init": "^1.0.1",
		"@scullyio/ng-lib": "^1.0.0",
		"@scullyio/scully": "^1.0.5",
		"bootstrap": "^4.5.2",
		"cheerio": "^1.0.0-rc.3",
		"fast-xml-parser": "^3.17.4",
		"googleapis": "^45.0.0",
		"i": "^0.3.6",
		"jquery": "^3.5.1",
		"ngx-plug-n-play": "^1.2.1",
		"node-fetch": "^2.6.0",
		"npm": "^6.14.9",
		"prism": "^4.1.2",
		"prismjs": "^1.21.0",
		"querystring": "^0.2.0",
		"rxjs": "~6.6.2",
		"tslib": "^1.10.0",
		"xmlbuilder": "^15.1.1",
		"zone.js": "~0.10.2"
	},
	"devDependencies": {
		"@angular-devkit/build-angular": "~0.1000.5",
		"@angular/cli": "~10.0.5",
		"@angular/compiler-cli": "~10.0.8",
		"@notiz/scully-plugin-rss": "^1.1.0",
		"@types/jasmine": "^3.5.12",
		"@types/jasminewd2": "~2.0.3",
		"@types/prismjs": "^1.16.1",
		"codelyzer": "^5.1.2",
		"jasmine-core": "~3.5.0",
		"jasmine-spec-reporter": "~4.2.1",
		"karma": "~5.0.0",
		"karma-chrome-launcher": "~3.1.0",
		"karma-coverage-istanbul-reporter": "~2.1.0",
		"karma-jasmine": "~3.0.1",
		"karma-jasmine-html-reporter": "^1.4.2",
		"protractor": "~7.0.0",
		"ts-node": "~8.3.0",
		"tslint": "^6.1.3",
		"typescript": "~3.9.7"
	}
}

I can’t see you function code but, in the actual function folder, require node-fetch. I had this issue with other packages when I required them in the function they worked.

If youve already done this, can you share the code please

Here’s the function code, minus some unneeded details here. I’m requiring node-fetch a the top of the file and then using it like normal.

const fetch = require('node-fetch');

const PACKAGES = [
	...
];

function urlBuilder(packageName, start, end = '') {
	...
}

async function getData() {
	const promiseArray = [];

	try {
		for (const package of PACKAGES) {
			const url = urlBuilder(package.name, package.start);
			promiseArray.push(fetch(url));
		}

		const results = await Promise.all(promiseArray);
		const data = [];
		for (const res of results) {
			const json = await res.json();
			data.push(json);
		}
		return data;
	} catch (error) {
		console.error(error);
	}
}

exports.handler = async function (event, context, callback) {
	if (event.httpMethod !== 'GET') {
		return { statusCode: 405, body: 'Method Not Allowed' };
	}

	try {
		const data = await getData();
		const stringified = JSON.stringify(data);
		const returnObj = { statusCode: 200, body: stringified };
		console.log('returnObj:', JSON.stringify(returnObj, null, 2));
		return returnObj;
	} catch (error) {
		return {
			statusCode: 500,
			headers: {
				/* Required for CORS support to work */
				'Access-Control-Allow-Origin': '*',
				/* Required for cookies, authorization headers with HTTPS */
				'Access-Control-Allow-Credentials': true,
			},
			body: `An error occurred: ${String(error)}`,
		};
	}
};

hey there,

can you give this a read through and see if it is helpful? seems like changing the require statement might be necessary.

I’m trying to use netlify and its lambda function feature to run a node function with dependencies. Based on https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/ , I have in my functions/submission-created.js:

const fetch = require('node-fetch');

exports.handler = async event => {

    const email = JSON.parse(event.body).payload.EMAIL
    const asking = JSON.parse(event.body).payload.ASKING
    console.log(`Recieved a submission: ${email}`)
    ....

When I look under my netlify websites functions tab , I see:

11:40:35 PM: 2020-12-02T04:40:35.092Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/submission-created.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'","Require stack:","- /var/task/submission-created.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:1015:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)","    at Module.load (internal/modules/cjs/loader.js:879:32)","    at Function.Module._load (internal/modules/cjs/loader.js:724:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}

my package.json (after running npm init):

{
"name": "site",
"version": "1.0.0",
"description": "",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
 },
"author": "",
"license": "ISC",
"dependencies": {
  "dotenv": "^8.2.0",
  "node-fetch": "^2.6.1"
}
 }

The package structure looks like:

enter image description here

here is the repo :

https://github.com/kc1/test2

I’ve tried putting the node modules folder and package.json in multiple places and repushing the repo, but I’m still getting the error above. What am I doing wrong?

hi there, i am moving this thread as it is basically the same question as:

Yeah, I tried to change my require to

const fetch = require('node-fetch').default

And that didn’t do anything. Again, it works locally but not when deployed. This also worked up until early this week when I deployed an updated site and moved off Jekyll.

Thanks for your help. I read through the other thread and tried both

    const fetch = require('node-fetch').default

and 

    const fetch = request('node-fetch').default

still getting the same error...

You are committing node_modules to the repo? That isn’t typically how it is done, I have a feeling that would be causing issues. When netlify runs your code, it needs to install those dependencies, I think you’d need a build command like netlify-lambda build functions ./built-functions etc?