Skip to content
Advertisement

How to make multiple fetch requests inside Firebase functions?

I am trying to make 2 fetch requests inside a function which runs periodically.

exports.scheduledPay = functions.pubsub.schedule('1 of month 07:00').timeZone('America/New_York').onRun((context) => {
  //1. fetch for getting token ...
  //2. fetch for making Paypal batch request using that token
    fetch("https://api.sandbox.paypal.com/v1/payments/payouts", {
      method: 'POST',
      headers: {"Authorization":"Basic QWJ4aUhTaWM5cmp2NUpQdEV2WUhaMi1hWmVySWFoTHdDVDEza004UURLY3RMWGtXN3lpTFRfVGpFVllVMXB5NFhKcGtxXzdYSVpYRmhkaFc6RVBUbUVZSWg2OE1FVG9FSjEyT0lHdzFKWkFGNTVza2Q2SjNiRmpLYkxMTEJiOTY3akRhQkdRREt1S29yTWN4amZ3Rm00X0VCa1dvUzJkejn="},
      body: {"grant_type":"client_credentials"},
      redirect: 'follow'
    })
    .then(response => {return response.text()})
    .then(result => {console.log(result);
      return null;
    })
    .catch(error => console.log('error', error));
}

However, I keep on getting this error.

ReferenceError: fetch is not defined
    at exports.scheduledAward.functions.pubsub.schedule.timeZone.onRun (/workspace/index.js:230:5)
    at cloudFunction (/workspace/node_modules/firebase-functions/lib/cloud-functions.js:130:23)
    at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:199:28)
    at process._tickCallback (internal/process/next_tick.js:68:7) 

Advertisement

Answer

Cloud Functions run in a nodejs JavaScript environment. This is very different than browser JavaScript environments. You won’t have access to the fetch() function that browsers provide – that explains the error message.

What you will need to do instead is use some other type of HTTP client library built for nodejs. There are a lot of popular options out there, and I recommend doing a web search to find one.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement