Skip to content

How to fix 'ReferenceError: fetch is not defined' in Node.js

Dec 2, 2022Abhishek EH2 Min Read
How to fix 'ReferenceError: fetch is not defined' in Node.js

Have you been a front-end developer and recently started using Node.js? Have you used fetch to get the data from an API in Node.js the way you do in the front-end? Then most likely you would have encountered the following error:

1ReferenceError: fetch is not defined

Replicating the issue

First, let's replicate the issue. You can update the index.js to the following and run node index.js, you should be able to see the error.

1const fetchRandomUser = () => {
2 fetch("").then(async response => {
3 const data = await response.json()
4 console.log({ data })
5 })

Understanding the issue

Why does the above code work perfectly fine in the front-end (or browser) and fails in Node.js? This is because fetch is a Web API and it is not supported in the version of the Node.js installed on your machine.

Fixing the issue

There are 2 ways in which you can fix this issue:

Upgrading Node.js to v18 or later

Starting version 18, Node.js has started supporting fetch API. You can download the latest Node.js version from here and install it.

Using node-fetch library

Previous to the release of Node.js v18, the most popular way to use fetch in Node.js is to install the node-fetch library.

Let's go ahead and do it.

1npm i node-fetch

Now update the index.js to import fetch:

1import fetch from "node-fetch"
3const fetchRandomUser = () => {
4 fetch("").then(async response => {
5 const data = await response.json()
6 console.log({ data })
7 })

Note that we have used the import syntax because starting v3, node-fetch is an ESM only module. If you are using Node.js version earlier than 12.20.0 or need to use CommonJS syntax (require syntax: const fetch = require("node-fetch")), then you can install node-fetch version 2 using npm i node-fetch@2.

Update the package.json with type as module. This is required to tell Node.js to use ESM Module syntax, since, by default, Node.js uses CommonJS syntax.

2 "name": "nodejs-referenceerror-fetch-is-not-defined",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "type": "module",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "keywords": [],
11 "author": "",
12 "license": "ISC",
13 "dependencies": {
14 "node-fetch": "^3.2.9"
15 }

Now if you run the code, it should work properly.

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2023 CodingDeft.Com