4

I'm trying to integrate Firebase Cloud Functions into my Ionic 3 App. The goal is to create a cloud function that will create a user using the admin SDK.

However, when triggering this function over HTTP it will execute twice only when passing data to it, if I just call the function with no data it executes once as intended.

Cloud Function Code:

const functions = require('firebase-functions');

exports.createUser = functions.https.onRequest((request, response) => {
  response.set('Access-Control-Allow-Origin', '*');
  response.set('Access-Control-Allow-Headers', 'Content-Type');
  console.log(request.body);
  response.status(200).send('Hello from Firebase!');
});

HTTP Request:

axios.post(functionURL, {
  data: 'some data'
})
.then(res => {
  console.log(res.data);
})
.catch(err => console.log(err));

The HTTP request above works as intended and I see "Hello from Firebase! " only once in the console, however when I look at the functions logs it's showing it's being executed twice.

enter image description here

I'm very new to Firebase Cloud Functions so any input or suggestions would be greatly appreciated!

Péttrin Miranda
  • 259
  • 3
  • 13
Coady
  • 101
  • 8
  • Are you certain that the client isn't somehow triggering it twice? HTTP functions come with an at-least-once guarantee per request. They are either triggered 0 or 1 time with each request. This type of question gets posted from time to time, and it's always the client. – Doug Stevenson Mar 27 '19 at 15:36
  • I'm almost 100% sure too that your client is calling it again somewhere... – Sergio Flores Mar 27 '19 at 16:03
  • FYI, Cloud Functions might execute multiple times by design. See [this code sample](https://github.com/GoogleCloudPlatform/cloud-functions-reliability-nodejs/blob/master/idempotency/index.js) – xenospn May 12 '19 at 03:00

1 Answers1

5

Solved

Solution found here: Cloud Functions for Firebase triggering function on CORS preflight request

As I was sending the data as application/json it was triggering a CORS preflight request, which is exactly what was causing the function to execute twice when passing data.

To bypass this, I simply sent the data as a application/x-www-form-urlencoded string like this:

const dataStr = JSON.stringify(objectToPass);

axios({
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: `data=${dataStr}`
})

And then parse the body back into an object in the function like this:

const data = JSON.parse(request.body.data);
Coady
  • 101
  • 8
  • Good job on finding the solution to your own question. As soon as you are able to, please mark it as a solution to give more visibility to the question. – Andrei Cusnir Mar 29 '19 at 09:57