Search code examples
javascriptnode.jsnunjucks

Cannot set headers after they are sent to the client nunjucks/express


I am running the front-end separately from the node server, everytime I update the firebase database, the node client app crash with this error:

_http_outgoing.js:470

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

My code is a very basic api call

app.get("/:user/", cors(), (request, response, next) => {
  var user = request.params['user'];
  console.log(user);
  firebase.database().ref(`/master/${user}/`)
  .on('value', snapshot => {
      var obj = snapshot.val()
      var data = []
      var keys = []
      for (let a in obj) {
        data.push(obj[a])
        keys.push(a)
      }
      response.render('index.html', { data });
    });
})

Solution

  • Use .once instead of .on, to get the current state of the snapshot, instead of retrieving every update. doc