Explain Codes LogoExplain Codes Logo

Referenceerror: fetch is not defined

javascript
fetch
nodejs
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 21, 2024
TLDR

Eradicate the ReferenceError: fetch is not defined by integrating node-fetch into your Node.js codebase:

npm install node-fetch
const fetch = require('node-fetch');

Now, you can wield the power of the browser's fetch API for HTTP requests in Node.js, just like invoking a Patronus in the world of Dementors.

Heavy-duty explanation

ES Module syntax

If ES Modules are your choice of syntax, pull fetch into your Node.js code like this:

import fetch from 'node-fetch'; // ES Modules? More like E'sy Modules, right?

Setting fetch as global

In cases where you want fetch in scope everywhere to avoid summoning it in every file:

import fetch from 'node-fetch'; globalThis.fetch = fetch; // “Alright everyone, fetch is now global. You can thank me later!”

Just remember that with great power (of global variables) comes great responsibility.

Version-specific strategies

Node.js v17 and fetch

Once you step into Node.js v17 zone, fetch becomes available as an experimental feature. Just start node with the --experimental-fetch flag:

node --experimental-fetch script.js // "Fetch? Oh, you mean my experimental friend over there?"

fetch in Node.js v18 and onwards

From Node.js v18 onwards, fetch comes as a native feature. No packages required!

fetch('https://example.com') // "Fetch walks into a bar... and nails it natively!"

Alternate solutions for different needs

CommonJS compatibility with Node-fetch v2

In a galaxy where you are still riding the CommonJS wave:

const fetch = require('node-fetch'); // "Fetch, do you copy? Over."

Remember, [email protected] is your co-pilot here. The newer versions might not play nice with the good ole' require().

Cross-universe fetch with Cross-fetch

If consistency across Node.js, browsers, and React Native is your endgame, cross-fetch is your hero:

import fetch from 'cross-fetch'; // "Cross-fetch to base, we are go for universal fetch!"

Good old HTTPS module

Before there was fetch, we had HTTP (HTTPS for secured ones) requests with Node’s https module:

const https = require('https'); https.get('https://example.com/api', (res) => { // "Hello HTTPS, my old friend!" });

Safety first: Best practices

Dealing with API requests?

  • **Catch em errors**: Use try-catchblocks or attach.catch()` to promises.
fetch(url).catch(error => console.error('Fetch error: ', error)); // "You catch 'em, before they catch you!"
  • Check before trusting: Always ensure the response is what you're expecting.
  • Async/Await is your friend: It simplifies the syntax for Promises that fetch returns.

Avoid creating global dependencies. They may lead to spooky bugs and a messy global scope.