Published on

Fix "fetch is not defined" error in external packages

Authors

If you're on older versions of Node.js, then chances are you might be running into an error when you try to use fetch natively.

"ReferenceError: fetch is not defined" for external packages

The fix is straight forward. Use node-fetch

Dependency

npm install node-fetch

By assigning fetch to global, it will resolve the issue even for external packages

Polyfill for ESM

import fetch, { Headers, Request } from "node-fetch";

if (!globalThis.fetch) {
  globalThis.fetch = fetch;
  globalThis.Headers = Headers;
  globalThis.Request = Request;
}

// Or the old way like this 👇
// global.fetch = fetch;

Polyfill for CommonJS

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

Happy fixing fetch!