Meteor.onConnection - Get userId on disconnect


I’m trying to access the user id if the user disonnects, to mark him as offline. This is my current code:

Meteor.onConnection((obj) => {

 obj.onDisconnect(() => {



The problem is, that this.userId is undefined. Is there any other way to get the disconnect event?


You could try tracking the connection id from the onConnect callback. This can be used to index into the Meteor.server.sessions object to get a bunch of useful information - including the userId if there is a user associated with that connection.

 Meteor.server.sessions[connectionId].userId; // returns (for example): 'RphM4g8DqAmBJgHfx' or null if no userId


thanks for the reply. I’ve decided to track the user status within a global subscription, f.e.:

Meteor.publish("contacts", function ()  {

    if(!this.userId) {
        return false;

    var userId = this.userId;

    this._session.socket.on("close", Meteor.bindEnvironment(function()
        //Doing something if the user disconnects.

    return Contacts.find({user1:this.userId});