Cannot set headers after they are sent to the client when adding data to firebase

Viewed 56

I've been having this error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 
at ServerResponse.setHeader (_http_outgoing.js:533:11)

After I added an update firebase code in a socket.io

io.on('connection', socket => { 
... 

socket.once('myEvent', async (dataToSend) => {
 try {
    await db
    .collection('myCollection')
    .doc('myDoc')
    .update({keyToUpdate: dataToSend})
    } catch (err) {
       console.log(err)
    }
  }
}

I thought the problem was with socket so I did the same logic but with a POST route outside the socket, and got the same error, I tried adding a return but didn't work

I suspect it could be because this function is a promise and I'm not handling asynchronous behaviour well, or because the server is acting as a stream thanks to socket.io and this firebase function doesn't like that.

I have other firebase functions in the code but they are get requests (.onSnapshot()) the error only happens with data adding firebase functions (.set(), .add(), .update())

Would appreciate some help here, thanks.

1 Answers

Fixed, didn't exactly knew how onSnapshot works, so everytime an update was made it triggered its callback which was sending info and triggering the error.

Changed to .get().then() and that fixed it

Related