onCall cloud function returns ‘Data cannot be encoded in JSON. NAN’

I have an onCall function that looks like this..

exports.getResults = functions.https.onCall((data, context) => {
  const admin = context.auth.token.admin
  const uniqueId = context.auth.uid
  const doc = db.collection('collection').doc(data.docId)

    return doc
      .then(querySnapshot => {
        return querySnapshot.docs.map(doc => {
          const doc = doc.data()
          const collectionDoc = {
          return collectionDoc

my console.log prints the doc I am requesting as an object, so I’m not sure what the issue is?


I understand that you have this error in Firebase Function logs. This means that you are returning NaN somewhere in the object. According to this article:

To send data back to the client, return data that can be JSON encoded.

It may depend on implementation, however here NaN is cannot be JSON encoded. (Found something about it in Wikipedia – Data types and syntax – Number).

You can easily replicate this problem by deploying function with not initialized variable:

exports.getResults = functions.https.onCall(() => {
        var number;
        var value = number+1;
        return {
                "text": "test",

In the example I added undefined to number the result will be NaN. Of course there might be other functions that will return NaN as well. Anyway if you deploy example above, it will log the same error “Data cannot be encoded in JSON. NaN”. I think this is most easily to be overlooked in the code.

I think you have to carefully check all data that you are returning.