Wait for firebase email success/failure before sending response


In my firebase app i’ve made it so a user can send an email to another user. I’ve got a node server listening for these requests and sending them through FireBase and the Trigger Email extension. Once i insert a document like this —

  to: `${req.body.toEmail}`,
  message: {
    subject: "here is a subject",
    html: `here is a message`,
.then((response) => {
    return res.status(200).json({
      message: "email sent!"

Trigger Email does some magic (I think it’s utilizing a cloud function) to then begin to update the document once it’s created.

The document will get updated with a property called state that will either be ERROR or SUCCESS. I need to wait until that field gets added and updated before returning a response to the client.

Anyone dealt with this before?


The Trigger Email extension indeed use Cloud Functions and all functions instances run independent of each other. One workaround this would be to return ID of new document created in mail collection and listen changes to that document on client side:

return res.status(200).json({
  message: response.id // ID of new document

Then on your client side you can listen for any updates to this document:

    .onSnapshot((doc) => {
      const { state } = doc.data()
      if (state === "SUCCESS") {
        alert("Email Sent")
      } else if (state === "ERROR") {
        alert("Failed to send email")
      } else {
        alert("Email yet to be sent")

If the "state" field is missing then the trigger email extension has no yet completed and updated back the mail document so you’ll have to wait until another update is received by the listener. You could use the same logic in the first function itself and return the response once the document is updated but it’ll just lead to additional Cloud function time charges might result in an error just in case you hit the timeout for some reason.

Answered By – Dharmaraj

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.