broadcast to room not working in disconnect

I would like to inform other client in the room when someone gets disconnected.

Here is my code:

socket.on('disconnect', function(){ 
    var user = authedUsers[socket.id];
    socket.broadcast.to(user.room).emit('message', {user: user, message: user.display_name + ' has been disconnected.'});
});

But I am getting this error:

RangeError: Maximum call stack size exceeded
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0

The error is that when the event disconnect is called, the socket is already closed.

So when you call the buggy line, it search to send with a closed socket, and for some reason end up making a call stack overflow.

You should send the message of deconnection before deconnecting the socket : )