Hello,
I have a simple Function in my website determined-hoover-41f81b that used to work flawlessly (it sends an online contact form to me as email via Sendinblue). At the moment I’m stuck with an error on line 1 with node-fetch
, which I seem unable to import in any way.
I’ve read that with node-fetch
v3.x it’s not possible anymore to:
const fetch = require('fetch');
In fact this triggers the error:
Error: require() of ES Module /Users/davidebarranca/Documents/Sites/CCExtensions/node_modules/node-fetch/src/index.js from /Users/davidebarranca/Documents/Sites/CCExtensions/functions/send-contact-form/send-contact-form.js not supported.
Instead change the require of index.js in /Users/davidebarranca/Documents/Sites/CCExtensions/functions/send-contact-form/send-contact-form.js to a dynamic import() which is available in all CommonJS modules.
I’ve read in this forum here that the recommended way is to:
import fetch from "node-fetch";
… and set node_bundler = "esbuild"
in the netlify.toml
. Which I did, resulting in the error:
SyntaxError: Cannot use import statement outside a module
I’ve then resolved to use the suggestion from the first error message (dynamic import) and I’ve grabbed the snippet from the node-fetch
documentation page, so I’m now trying:
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
This result in a joke of an error:
SyntaxError: Unexpected token o in JSON at position 1
JSON.parse (<anonymous>)
Object.exports.handler (/Users/davidebarranca/Documents/Sites/CCExtensions/functions/send-contact-form/send-contact-form.js:11:35)
Object._executeSync (/usr/local/lib/node_modules/netlify-cli/node_modules/lambda-local/build/lambdalocal.js:286:47)
/usr/local/lib/node_modules/netlify-cli/node_modules/lambda-local/build/lambdalocal.js:95:26
new Promise (<anonymous>)
Object.execute (/usr/local/lib/node_modules/netlify-cli/node_modules/lambda-local/build/lambdalocal.js:87:16)
Object.invokeFunction (/usr/local/lib/node_modules/netlify-cli/src/lib/functions/runtimes/js/index.js:58:36)
NetlifyFunction.invoke (/usr/local/lib/node_modules/netlify-cli/src/lib/functions/netlify-function.js:123:41)
processTicksAndRejections (node:internal/process/task_queues:96:5)
async handler (/usr/local/lib/node_modules/netlify-cli/src/lib/functions/server.js:154:33)
I’m hence unable to fetch anything (I’ve discovered it the hard way, i.e. people complaining on forums that my contact form doesn’t work). What am I doing wrong here?
Thank you very much!
Davide