Cloud Function writing to Firebase Realtime Database times out

Viewed 2833

I can see a new entry is added as soon as I get the URL, but the request hangs and times out. Why?

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

admin.initializeApp(functions.config().firebase);

exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
})

The code is based on the following example. https://firebase.google.com/docs/database/admin/save-data

Result

{"error":{"code":500,"status":"INTERNAL","message":"function execution attempt timed out"}}
1 Answers

Cloud Functions triggered by HTTP requests need to be terminated by ending them with a send(), redirect(), or end(), otherwise they will continue running and reach the timeout.

From the terminate HTTP functions section of the documentation on HTTP triggers:

Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system. See also Sync, Async and Promises.

Therefore, in your example, you can end the request by sending a response:

exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
    response.status(200).send("OK!");
})
Related