Skip to content
← Back to Community
How do I fix ReferenceError: fetch is not defined
Profile icon
KarenTheKiller

I'm trying to use fetch on node.js but it's showing an error saying "ReferenceError: fetch is not defined"

Comments
hotnewtop
Profile icon
jamilnyc

My Solution

It was a little bit confusing at first, but after a lot of Googling around, I figured it out in this example here:

(Replace the %40 with @, I'm having a difficult time escaping it)
https://replit.com/%40jamilnyc/Making-Multiple-API-Requests-with-Promises?v=1

Steps

  • Add the node-fetch module using the Packages menu (on the left side of the editor, looks like a box).
  • This will create package.json. Edit your package.json file to add the property "type": "commonjs"
  • Use a dynamic import as shown in the documentation to make the fetch() function available.
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

In my version, I modified the dynamic import example from the documentation to use regular functions because I find the arrow notation => a little harder to read. That's just a personal preference, you can use it as-is from the documentation if you like.

Profile icon
SixBeeps

You might need to actually install the module before using it. Could you link the Repl?