Search code examples
javascriptnode.jsexpresspolyfills

How to provide a polyfill to a node module


I'm trying to use the unsplash-js module in a NodeJS/express server. As the docs say: "This library depends on fetch to make requests to the Unsplash API. For environments that don't support fetch, you'll need to provide a polyfill". I've tried something like that, which I am quite ashamed of showing, but for the sake of learning I will

const Unsplash = require('unsplash-js').default;
const fetch = require('node-fetch');

Unsplash.prototype.fetch = fetch;

const unsplash = new Unsplash({
  applicationId: process.env.UNSPLASH_API_KEY,
});

And also this

Node.prototype.fetch = fetch;

But of course, nothing worked. How do I do that?


Solution

  • You need to set fetch to global variable like below:

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