Search code examples
javascriptnode.jsamazon-web-servicesaws-lambda

node-fetch not working with AWS lambda function ("cannot find node-fetch")


Basically I am trying to invoke a lambda function from an API Gateway. The API is called from an index.html file I made that calls the api with a button click and returns values (ideally the weather). I can get it to return some text values but whenever I try to actually call an API with the lambda function using node-fetch function it gives me an error saying "cannot find node-fetch module."

const fetch = require('node-fetch')

module.exports.getTulsaCurrentWeather = (event, context, callback) => {

//API endpoint
const endpoint = `http://api.openweathermap.org/data/2.5/weather? 
APPID=${process.env.APPID}&q=Tulsa&units=imperial`;

fetch(endpoint)
.then( res => res.json() )
.then( body =>  {
const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*",
  },
  body: JSON.stringify({ temperature: body.main.temp })
};

callback(null, response);
});
};

Solution

  • See How do I build a Lambda deployment package for Node.js?

    A common error with Lambda functions in Node.js is "cannot find module." This error is usually caused when your deployment package doesn't have the correct folder structure for the Lambda service to load your modules and libraries, or it has incorrect file permissions. (Lambda requires global read permissions.)

    Follow these instructions to build a deployment package that includes the function code in the root of the .zip file with read and execute permissions for all files.

    Note that your code wouldn't run outside of Lambda either, for example on your own machine, unless you had previously installed the node-fetch package from NPM.

    The analogous process in AWS Lambda is to package and upload your third-party dependencies, or deploy the packages to a Lambda Layer and configure your Lambda function to use that layer. Lambda will not npm install node-fetch for you.