Pierre Heurtebise
Pierre Heurtebise

Reputation: 27

Error in firebase function that generates custom token

I'm trying to implement a Firebase function that generates a custom token for my app. But I keep getting the following error message :

Error: could not handle the request

Or it ends up in timeout.

Do you have any idea of what could be wrong with my code hereafter ? I'm trying it with a 'test' uid.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

exports.customFunction = functions.https.onRequest((data, context) => {
  return admin.auth().createCustomToken('test')
  .then(customToken => {
      console.log(`The customToken is: ${customToken}`);
      return {
        status: 'success', 
        customToken: customToken
      };
  })
  .catch(error => {
      console.error(`Something happened buddy: ${error}`)
      return {
        status: 'error'
      };
  });
});

Upvotes: 0

Views: 143

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

Your Cloud Function is an HTTPS one. In order to terminate it you need to call res.redirect(), res.send(), or res.end() as explained in the doc.

In your code you actually return the Promises chain: this is the correct way to terminate Cloud function triggered by background events (which is not the case of an HTTPS Cloud Function which is triggered by a call to the URL it exposes).

So, the following changes should do the trick (untested):

exports.customFunction = functions.https.onRequest((req, res)(data, context) => {
  admin.auth().createCustomToken('test')  // No need to return 
  .then(customToken => {
      console.log(`The customToken is: ${customToken}`);
      response.status(200).send({
        status: 'success', 
        customToken: customToken
      });
  })
  .catch(error => {
      console.error(`Something happened buddy: ${error}`)
      response.status(500).send(error);
  });
});

Note that with an HTTPS Cloud Function, the objects you pass to the handler are not the Firebase data and context objects but the Express.js request and response objects.

So it is more clear to write

exports.customFunction = functions.https.onRequest((req, res) => {...});

instead of

exports.customFunction = functions.https.onRequest((data, context) => {...});

Upvotes: 1

Related Questions