Getting "must use import to load ES module" when using `node-fetch` in Netlify Functions

Hi @spacecrafter3d

I came across this a few days ago testing something locally. As per Loading and configuring the module

node-fetch from v3 is an ESM-only module - you are not able to import it with require() .

So you would now change

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

to

import fetch from 'node-fetch';

In doing so, you would need to change the node_bundler environment variable to esbuild e.g. in a netlify.toml file

[functions]
  node_bundler = "esbuild"

In order to use

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

you need to use node-fetch@2 (see npm docs) or load v3 asynchronously (from npm docs)

const fetch = (...args) => import('node-fetch')
              .then(({default: fetch}) => fetch(...args));
5 Likes