"Error: Cannot find module 'node-fetch'" when deploying function

I was having this problem also and tried the steps from here, Netlify Functions Can't find module and Cannot use node-fetch in lambda function :

  • Installing deps in project root
  • Installing deps in functions specific folder e.g. having functions/testfunc/package.json and changing command to install these and also
  • Changing const fetch = require('node-fetch') to:
    • const fetch = require('node-fetch').default
    • const fetch = request('node-fetch').default
  • Adding node-fetch peer dependency encoding

However, none of these things worked. I then tried seeing if copying the Fetch example from playgrounds would work and it did. The issue was that I had a variable in my function static

const static = ['/blog', '/about', '/'];

For some reason having a variable called static causes

Error: Cannot find module 'node-fetch'

This can be replicated by:

  1. Creating a new function, test.js with the code from the Fetch example in Functions playground
  2. Installing node-fetch in the projects root dependecies
  3. Deploying to netlify with automatic git commit deploys
  4. Going to /.netlify/functions/test and seeing the joke
  5. Change the function to:
const fetch = require("node-fetch");

const API_ENDPOINT = "https://icanhazdadjoke.com/";

exports.handler = async (event, context) => {
  const static = ["hello", "goodbye"];

  return fetch(API_ENDPOINT, { headers: { Accept: "application/json" } })
    .then((response) => response.json())
    .then((data) => ({
      statusCode: 200,
      body: data.joke,
    }))
    .catch((error) => ({ statusCode: 422, body: String(error) }));
};
  1. Commit and deploy
  2. Go back to /.netlify/functions/test and you’ll see the error

@perry is this the expected behaviour? No other variable causes this problem and the function works fine in dev (netlify dev and going to localhost)