Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using node-fetch in js file in browser and in node

I have built a class to do some fetch from an API and construct a suited response for my app.

I use this file both in an app that run on the browser, and on a CLI app to work on the terminal.

As I built the browser app first, there was no import to node-fetch. Now when I try to use this .js file in my CLI app, it returns error saying fetch is not defined.

If I add to my api client .js file: import fetch from "node-fetch" then now my browser app is not working as well, print to the console:

Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".

Is there anyway to apply fetch and use the same file for both?

Thanks

like image 556
Avr.Nadav Avatar asked Dec 17 '25 15:12

Avr.Nadav


2 Answers

For use-cases where you cannot update Node, you can conditionally import the Fetch API.

let fetch = globalThis?.fetch;

if (!fetch && process?.versions?.node) {
  fetch = (await import('node-fetch')).default;
}

console.log(fetch);

Note that this uses top-level await.

like image 136
Besworks Avatar answered Dec 20 '25 06:12

Besworks


Your options are:

  • Use Node.js 18 or newer which has native support for fetch
  • Use a tool like Webpack which can pick different versions of fetch depending on the target environment.

The former option is much easier (at least from a technical POV)!

like image 44
Quentin Avatar answered Dec 20 '25 07:12

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!