Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
The "ReferenceError: fetch is not defined" occurs when the fetch()
method is
used in an environment where it's not supported - most commonly Node.js.
To solve the error, install and import the node-fetch
package, which
provides a fetch()
compatible API in the Node.js runtime.
Note that the global fetch
variable is available in
Node.js starting at version 18.
You can check your version of Node.js with the node -v
command.
node -v
If you use a Node.js version older than 18
, you can either download and
install the LTS version from nodejs.org or install and
use the node-fetch
package.
node-fetch
package.If your project doesn't have a package.json
file, create one in your project's
root directory:
# ๐๏ธ only run this if you don't have package.json file yet npm init -y
Now install the node-fetch
library by running the following command.
# ๐๏ธ with NPM npm install node-fetch # ๐๏ธ only if you use TypeScript npm install @types/node-fetch --save-dev # -------------------------------------------- # ๐๏ธ with YARN yarn add node-fetch # ๐๏ธ only if you use TypeScript yarn add @types/node-fetch --dev
Now you can import and use the module just like you would use the fetch() method in the browser.
import fetch from 'node-fetch'; async function getUser() { try { const response = await fetch('https://randomuser.me/api/'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } console.log(await getUser());
At the time of writing, to use ES6 module imports and exports in a NodeJs
project, you have to set the type
property to module
in your package.json
file:
{ "type": "module", // ... ๐๏ธ rest }
If I run my NodeJs script, I get the result from calling the API.
node-fetch
package are only compatible with the ES6 Modules syntax of import/export. If you use an older NodeJs version, install version 2 of the node-fetch
package.Only do this if you use an older NodeJs version and want to use the require
syntax instead of import/export
.
npm install node-fetch@2
We installed version 2 of the node-fetch
package.
Make sure you don't have the type
property set to module
in your
package.json
file.
Now you can import the fetch
package using the older require
function.
// ๐๏ธ Using older require syntax const fetch = require('node-fetch'); async function getUser() { try { const response = await fetch('https://randomuser.me/api/'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } }
We had to install version 2
of the node-fetch
package to be able to use the
require
syntax in our NodeJs application.
It's best to stay consistent with imports between your client and server-side code. However, this approach gets the job done if you have to support an older version of NodeJs.