DEV Community

Discussion on: The NodeJS 18 Fetch API

Collapse
 
lexlohr profile image
Alex Lohr

For libraries, I found a rather nice pattern to allow users to only install node-fetch if they need it:

// package.json
{
  "peerDependencies": {
    "node-fetch": "*"
  },
  "peerDependenciesMeta": {
    "node-fetch": {
      "optional": true
    }
  }
}

// Run before you use fetch:
if (!globalThis.fetch) {
  Object.assign(globalThis, {
    fetch: (...args: any[]) => {
      try {
        const fetch = require("node-fetch");
        Object.assign(globalThis, { fetch });
        return fetch(...args);
      } catch (e) {
        console.warn(
          '"\x1b[33m⚠️ package missing to run fetch on the server.\n Please run:\x1b[0m\n\nnpm i node-fetch\n"'
        );
        Object.assign(globalThis, { fetch: () => Promise.reject() });
        return Promise.reject();
      }
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

This way, users get a helpful message if they forget to install node-fetch and you can avoid superfluous dependencies.