Fix - node-fetch Error [ERR_REQUIRE_ESM]: not supported


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Fix - node-fetch Error [ERR_REQUIRE_ESM]: not supported #

The node-fetch error "[ERR_REQUIRE_ESM]: require() not supported" occurs because the node-fetch package has been converted to be an ESM only package in version 3, which means that the package cannot be imported with require() anymore.

node fetch err require esm

To solve the node-fetch error "[ERR_REQUIRE_ESM]: require() not supported", use a dynamic import to import the node-fetch package or downgrade the version of the package to 2.6.6, which is the last version that is built with CommonJS.

Here is how to import the node-fetch package using a dynamic import in JavaScript and TypeScript.

// ✅ Do this if using JAVASCRIPT const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args)); // ✅ Do this if using TYPESCRIPT import { RequestInfo, RequestInit } from 'node-fetch'; const fetch = (url: RequestInfo, init?: RequestInit) => import('node-fetch').then(({ default: fetch }) => fetch(url, init));
Only use the import that applies to you. The first import if you use JavaScript or the second one if you use TypeScript.

You can read more about the breaking changes in the node-fetch package in their GitHub upgrade guide.

If your environment supports ES Modules, you should try to convert the require() import to ESM.

import fetch from 'fetch'; console.log(fetch)

But this might not work depending on your setup.

Alternatively, you can downgrade the node-fetch package to version 2.6.6 and still use the require syntax. Version 2 of the node-fetch package is built with CommonJS.

This is the recommendation in the upgrade guide because they continue to publish critical bug fixes for version 2.

To downgrade to version 2.6.6, open your terminal in the root directory of your project and run the following commands.

npm install node-fetch@2.6.6 # 👇️ NOTE: you only need this if using TypeScript npm install --save-dev @types/node-fetch@2.x

Make sure to only install the type definitions if you're using TypeScript.

The types are bundled with the node-fetch package starting at version 3.x, but if you use version 2.x, you have to install them separately.

Now you can use the require() syntax to import the node-fetch package.

const fetch = require('node-fetch'); console.log(fetch);
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.