To use import or require for importing node-fetch for Netlify Serverless Functions? Both give errors

When running the following serverless function in production…

const fetch = require('node-fetch')

const API_ENDPOINT = 'https://api.themoviedb.org/3/discover/movie?'
const API_KEY = process.env.MOVIEDB_API_KEY

exports.handler = async (event, context) => {
  try {
    console.log(response)
    const response = await fetch(API_ENDPOINT + API_KEY)
    const data = await response.json()
    return { statusCode: 200, body: JSON.stringify({ data }) }
  } catch (error) {
    console.log(error)
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Failed fetching data' }),
    }
  }
}

… I get an error message in the Netlify function log:

4:38:08 PM: 2022-01-14T15:38:08.520Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Error","errorMessage":"Must use import to load ES Module: /var/task/node_modules/node-fetch/src/index.js\nrequire() of ES modules is not supported.\nrequire() of /var/task/node_modules/node-fetch/src/index.js from /var/task/.netlify/functions/api.js is an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules.\nInstead rename index.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /var/task/node_modules/node-fetch/package.json.\n","code":"ERR_REQUIRE_ESM","stack":["Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/node_modules/node-fetch/src/index.js","require() of ES modules is not supported.","require() of /var/task/node_modules/node-fetch/src/index.js from /var/task/.netlify/functions/api.js is an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules.","Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /var/task/node_modules/node-fetch/package.json.","","    at new NodeError (internal/errors.js:322:7)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)","    at Module.load (internal/modules/cjs/loader.js:950:32)","    at Function.Module._load (internal/modules/cjs/loader.js:790:12)","    at Module.require (internal/modules/cjs/loader.js:974:19)","    at require (internal/modules/cjs/helpers.js:93:18)","    at Object.<anonymous> (/var/task/.netlify/functions/api.js:1:15)","    at Module._compile (internal/modules/cjs/loader.js:1085:14)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)","    at Module.load (internal/modules/cjs/loader.js:950:32)"]}

There is no “require” statement in the node-fetch package index.js file.

So I tried changing to an “import” statement in the serverless function file. Got this error message in the function log in the Netlify admin UI:

4:52:36 PM: 2022-01-14T15:52:36.655Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:200:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:242:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:1085:14)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)","    at Module.load (internal/modules/cjs/loader.js:950:32)","    at Function.Module._load (internal/modules/cjs/loader.js:790:12)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)","    at internal/main/run_main_module.js:17:47"]}

So my question is: How can I import/require fetch from node-fetch without errors?

Thanks,
/David

node-fetch dropped support for require() statement since version 3. So, you could stay on version 2, or add the following to your netlify.toml:

[functions]
  node_bundler = "esbuild"

Thanks, that worked! However, I ran into another issue that I cannot debug.

5:02:26 PM: 76545e0c INFO   Error: TypeError: fetch2 is not a function
    at Runtime.exports.handler (/var/task/.netlify/functions/api.js:5581:28)
    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)

I don’t have any instance of “fetch2” written in any of my project code. Specifically, no such statement exists in the .netlify/functions/api.js file.

Any ideas?

Thanks

Unfortunately not without seeing the repo.

Here you go: GitHub - davidronnlid/movie-project

Tagging @hrishikesh :slight_smile:

Hi @ronnlidd

Now that node_bundler = "esbuild" is set in the neltify.toml you can/need to change
from:

const fetch = require('node-fetch')

to:

import fetch from 'node-fetch'

This is covered in this post which takes information directly from the npm package page under the section: Loading and configuring the module.

2 Likes