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

ReferenceError: fetch is not defined error occurs when trying to “use the fetch() function in a Node.js environment, but fetch is not natively available in Node.js.”

In browsers, the fetch API provides a simple way to make network requests. But in Node.js, it is not available.

ReferenceError - fetch is not defined in Node.js

Reproduce the error

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

fetch('https://askjavascript.com')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Output

fetch is not defined in Node

How to fix the error

To fix the fetch is not defined error in Node.js, use libraries like “axios”, “node-fetch”, or the “built-in http and https modules to make HTTP requests.”

To use the fetch function in Node.js, you can install the node-fetch package:

npm install node-fetch

Now, we can use the fetch() method in Node.js.

If you are using ES6 imports:

import fetch from 'node-fetch';

This will give you a fetch() function in Node.js that works similarly to the browser’s fetch API.

Related posts

error: cannot find module ‘express’

cannot find module ‘fs/promises’ in Node.js

error: cannot find module ‘node:events’ in Node.js

nodemon clean exit – waiting for changes before restart

yarn requires node.js 4.0 or higher to be installed