How to exec code after res.send() in express server at Firebase cloudFunctions

893 Views Asked by At

I'm building an express server using the cloud functions, but I facing a problem with res.send(). In a common express server I can exec some code after res.send() but at my express server using the Firebase cloudFunctions res.send() closes my connection and I can't exec anything after that.

Here is what I need to do: In my server I have an endpoint to receive some data from Slack api dialog, and after that Slack Api is waiting for a empty response res.send(), so I need to send it. But I also need to save that data in my DB, and send a message in slack to my user "Your post was saved!" So what my endpoint does:

async function myEndpoint(req, res) {
    await savePayload(req.payload);
    await sendUserMessage(req.payload);
    res.send('');
}

But sometimes res.send() takes to long to start running and I get an error on slack, so I would like to do something like:

async function myEndpoint(req, res) {
    res.send('');
    await savePayload(req.payload);
    await sendUserMessage(req.payload);
}

But as I said, after res.send('') my connection is closed and the next lines doesn't run. Do you know how can I work around that ?

1

There are 1 best solutions below

4
Michael Bleigh On BEST ANSWER

HTTP functions immediately terminate execution once the response is completed -- this is fundamental architecture for Cloud Functions, so there is no way around it. You will need to either:

  1. Optimize your code paths such that the empty response is always sent under the deadline, or
  2. Trigger a background function execution that will do the work asynchronously, then respond. This could be done by e.g. writing to Cloud Firestore or sending a Pub/Sub message