When building a Node.js app, you’ll get the Javascript error “ReferenceError: fetch is not defined” when trying to use the fetch API. This is because the fetch API is not implemented as a Node.js standard module (yet). There are a few different options for dealing with this:
- Use a 3rd party module
- Use the standard Node.js module,
https
Which of these work-arounds you choose depends on your situation. If you’re porting code to Node.js that used to run in a browser, you’ll want one of the 3rd party modules that implement the fetch API. If you’re writing something from scratch, it might be better for you to use axios, which is the de-facto standard for making HTTP requests in Node.
But before we get into potential solutions, let’s reproduce the error!
Reproducing the “fetch is not defined” Error
To cause the error to occur, we’ll simply attempt to fetch data from a URL the way you normally would in a web browser:
fetch("https://api.ipify.org?format=json")
.then(response => response.json())
.then(data => {
console.log(data.ip);
});
The above code will produce the following ReferenceError:
/home/user/example/index.js:1
fetch("https://api.ipify.org?format=json")
^
ReferenceError: fetch is not defined
at Object.<anonymous> (/home/user/example/index.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
As you can see, there’s no such thing as fetch by default on the Node.js platform.
How to Resolve “ReferenceError: fetch is not defined”
To fix this error, we have a couple different options. First, we can install a 3rd party Node module. This may not be ideal for all circumstances. If you need a drop-in replacement for the request API because your existing codebase is too large to refactor using a different method, you’ll want to go the 3rd party route. If you’re starting from scratch, you’ll probably want to use a different method instead.
Although just about every web browser implements fetch, Node does not. But that’s not because the developers were lazy. Node is meant to be server side software, whereas fetch, though simple and user-friendly, was only ever meant for the browser to be able to communicate back to the server the page was served from. Node instead provides built-in ways to do this, as well as very popular 3rd party modules that do not implement fetch, but handle HTTP(S) requests a different way instead.
First let’s take a look at the 3rd party modules we have available.
Use a 3rd Party Node Module
There’s many to choose from, but a few stand out from the crowd. The first one we have to look at is axios. While it’s not a one-for-one replacement for fetch (the methods are named differently), you’ll immediately notice some similarities.
axios
To install axios, run the following npm command in the root of your project directory:
Next, you’ll be able to import axios into your code and begin using it. See below for a re-work of our above nonfunctional example:
const axios = require("axios");
axios.get("https://api.ipify.org?format=json")
.then(response => {
console.log(response.data.ip);
});
// -> 123.45.67.8
Nice! For reference, we are using the web API at ipify.org for our examples. The expected response format is { "ip": "<your ip>" }. One nice thing you’ll notice about axios is it takes fewer lines of code to accomplish the same thing as fetch. This is because there’s no need to convert the response to JSON. It’s like magic!
Axios is a great option if you are starting a new project.
node-fetch
node-fetch is meant to serve as a drop-in replacement for the common fetch API that’s available in browsers. Again, you may need something like this when porting code that used the fetch API.
You can install node-fetch with the following command:
Note: we are installing node-fetch version 2 because it still supports the CommonJS require() syntax. If you use ESM syntax in your project, you can just npm install node-fetch and load the module with import fetch from ‘node-fetch’.
Once node-fetch is installed, we can import it into our code and use it just like we use fetch in the browser:
const fetch = require('node-fetch');
fetch("https://api.ipify.org?format=json")
.then(response => response.json())
.then(data => {
console.log(data.ip);
});
// -> 123.45.67.8
Perfect!
There’s a couple other fetch clones out there worth mentioning, but node-fetch is by far the most popular and well-maintained.
whatwg-fetch
whatwg-fetch will not work in Node.js, it’s meant only for the web browser. It’s a Node package because it’s meant to polyfill fetch for browsers that may not support it. It’s unlikely that this is what you’re looking for given the error you received, but if you do need to send fetch capability to your clients from the Node.js server side application, you can install it with the following command in your project directory:
Again, this is not for use server side. You’ve been warned!
cross-fetch
cross-fetch functions exactly like node-fetch. It’s not quite as popular, but it does seem to be maintained regularly.
You can install cross-fetch by running the following command in the root of your project directory:
Then, in your application, you can use cross-fetch as follows:
const fetch = require('cross-fetch');
fetch("https://api.ipify.org?format=json")
.then(response => response.json())
.then(data => {
console.log(data.ip);
});
// -> 123.45.67.8
Easy peasy.
Use Node.js Standard Module https
Of course, if you don’t want to install any 3rd party node modules, you could always use Node’s built-in https module. It’s much more clunky and verbose than axios for example, and it’s definitely not a drop-in replacement for fetch, but it works. See below for an example:
const https = require('https');
const req = https.get("https://api.ipify.org?format=json", res => {
let data = "";
res.on('data', d => {
data += d
});
res.on('end', () => {
obj = JSON.parse(data);
console.log(obj.ip);
});
});
// -> 123.45.67.8
Ugh. Kind of ugly, don’t you think? I’d highly recommend just installing axios and using that instead. But, if you’re constrained to whatever is in the default Node packages, this is your best bet. Oh well!
Conclusion
We covered what causes the Node error “fetch is not defined” and different possible solutions for it. Whether you’re starting a project yourself, or have inherited one that (for some reason) used fetch on the server side, one of the options above will suit your needs.
Table of Contents
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.
index.js
1const fetchRandomUser = () => {
2 fetch("https://randomuser.me/api/").then(async response => {
3 const data = await response.json()
4 console.log({ data })
5 })
6}
7
8fetchRandomUser()
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.
Now update the index.js to import fetch:
1import fetch from "node-fetch"
2
3const fetchRandomUser = () => {
4 fetch("https://randomuser.me/api/").then(async response => {
5 const data = await response.json()
6 console.log({ data })
7 })
8}
9
10fetchRandomUser()
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 [email protected].
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.
1{
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 }
16}
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.
Hello Guys, How are you all? Hope You all Are Fine. Today I am using fetch in my nodejs application and I am facing this error ReferenceError: fetch is not defined in nodejs. So Here I am Explain to you all the possible solutions here.
Without wasting your time, Let’s start This Article to Solve This Error.
Contents
- How ReferenceError: fetch is not defined in nodejs Error Occurs ?
- How To Solve ReferenceError: fetch is not defined in nodejs Error ?
- Solution 1: Install node-fetch
- Solution 2: accessible with a global scope
- Solution 3: Just use cross-fetch
- Summery
How ReferenceError: fetch is not defined in nodejs Error Occurs ?
I am using fetch in my nodejs application and I am facing this error.
ReferenceError: fetch is not defined
How To Solve ReferenceError: fetch is not defined in nodejs Error ?
- How To Solve ReferenceError: fetch is not defined in nodejs Error?
To Solve ReferenceError: fetch is not defined in nodejs Error Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:
- ReferenceError: fetch is not defined in nodejs
To Solve ReferenceError: fetch is not defined in nodejs Error Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:
Solution 1: Install node-fetch
Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:
npm install node-fetch
const fetch = require("node-fetch");
Now you can use fetch in your nodeJs application.
Solution 2: accessible with a global scope
If it has to be accessible with a global scope
global.fetch = require("node-fetch");
This is a quick dirty fix, please try to eliminate this usage in production code.
Solution 3: Just use cross-fetch
Just use cross-fetch
npm install --save cross-fetch
Usage With promises:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
fetch('//api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
})
.catch(err => {
console.error(err);
});
With async/await:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
(async () => {
try {
const res = await fetch('//api.github.com/users/lquixada');
if (res.status >= 400) {
throw new Error("Bad response from server");
}
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
})();
Summery
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also, Read
- SyntaxError: invalid syntax to repo init in the AOSP code.
When you ran your code, you saw the error messages: “ReferenceError: fetch is not defined“
As a result, after some research, we will present potential alternatives to programmers. Do not think too much, and let’s get going on correcting this error.
Under What Conditions Would This Issue Occur?
In general, fetch was created for one browser and converted to node.js in a third-party module that you appear to be lacking.
You may experience this issue while using fetch in the NodeJS application.
ReferenceError: fetch is not defined
You’ll need to utilize some external module, such as node-fetch, for this. Install this in the Node application, and add some lines to the head of your files that use the retrieve API.
Let’s take a closer look at stages using the three techniques listed below.
Method 1
The first way is to use the cross-fetch.
npm install --save cross-fetch
With promises, you can use this script.
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
fetch('//api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
})
.catch(err => {
console.error(err);
});
In the case of async/await, type this:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
(async () => {
try {
const res = await fetch('//api.github.com/users/lquixada');
if (res.status >= 400) {
throw new Error("Bad response from server");
}
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
})();
Method 2
You can use two syntaxes to address this problem.
Install this in the Node application as follows. Then add the second line
npm install node-fetch
const fetch = require("node-fetch");
Alternatively, you may add the following line at the files in which you are utilizing the retrieve API:
import fetch from "node-fetch";
Now you may implement fetch in the NodeJS application.
Method 3
Suppose it must be available on a worldwide scale. This is a fast and dirty workaround; please avoid using this in the codebase.
global.fetch = require("node-fetch");
Conclusion
In general, resolving the error “ReferenceError: fetch is not defined” is indeed not difficult.
We are confident that our answer will help you complete your project promptly. Hopefully, you’ll be able to produce even more incredible intellectual goods with nodejs.
Related articles
- Best Online best payout online casino uk casinos Us 2022
Posts Allege A 1,000% Crypto Incentive Up to $5,000 Legitimate Online casinos So why do Casinos Place Limitations? Books From the Slots43 Com best payout online casino uk As a result you should sign in atPoleStar Casino and you can complete throughout needed study. You will additionally be asked to make an initial put using […]
- Flea And Tick For Small Dogs Easy To Use
If you value animals and would like to make their lives better, consider buying the very best Family pet Supplies Andamp; Components. Numerous types of pet supplies and accessories is a wonderful way to ruin your pooch. From dog water and food dishes to dog collars, you can find all you need for your best […]
- Freispiele Abzüglich mr bet casino 10 Einzahlung 2022 Fix
Content Welches My Money Safe As part of A wohnhaft Casino Erreichbar? Echtgeld Maklercourtage Exklusive Einzahlung Ferner Freispiele Abzüglich Einzahlung Auf unserem Entree findet Das pauschal die eine aktuelle Register, within ihr die besten Online Boni via Freispielen & sekundär über Startguthaben pro Euch zugänglich sind. Unsereins von Bonus Waidmann werden immer unter das Ermittlung […]
- Backpage Replacement For Hookups Ad – Casual Hookup Website
Benaughty – More women than men Hookupdaters – 100% free online dating site Feeld – A safe space for users looking for friends with benefits Gaystryst – a platform for spontaneous hookups Onenightfriend – Fun casual dating app with an in-depth questionnaire HER – Top hookup app for lesbian women LGBTQ+ Zoosk – Meet local […]
- Competir De balde En España casino midas fraude Referente a Las Casinos En internet Sí Puedes
Content Preferible Casino Sobre Listo 2019 Players Deposit Has Never Been Credited To Her Casino Account Unique Casino Online Acerca de Argentina Bono Sobre Admisión Una vez ingresas a la plataforma de apuestas Unique, El bannière principal te recibe con la oferta sobre ofertas y no ha transpirado promociones , los cuales en un primer […]
Post Views:
479
Version of node.js…v14.15.4
PROBLEM
When I executed query in Apollo Server, I encountered this error message from the server.
"errors": [
{
"message": "fetch is not defined",
"locations": [
{
"line": 3,
"column": 1
}........
Enter fullscreen mode
Exit fullscreen mode
What does this mean? «fetch» is a method that handles request and response in asynchronous communication. Looks like this method is causing this error message.
const resolvers = {
Query: {
singlePokemon:async(parent, args) => {
let res = await fetch(`https://pokeapi.co/api/v2/pokemon/${args.id}`);
Enter fullscreen mode
Exit fullscreen mode
SOLUTION
The version of Node before 18 does not have the fetch API. So, you need to install an external module.
https://www.npmjs.com/package/node-fetch
npm install node-fetch
Enter fullscreen mode
Exit fullscreen mode