How to get server connection ID up to client?


#1

I’ve got this server-side code:

Meteor.onConnection(function (conn) {
  var connId = conn.id;

  console.log('welcome, ', connId);
  conn.onClose(function () {
    console.log('bye ', connId);
  });
});

How do I send the connection ID up to the client though? e.g.:

Template.myTemplate.events({
  'submit form': function (event, template) {
    var someData = [...];

    Meteor.call('createPost', someData, connectionId, function (error, result) {
    });
  });
});

#2

Anyone? :slight_smile:


#3

I believe Meteor.collection._lastSessionId already has it. But I can’t think of a good reason why you’d want to use this.

You can just get this variable in the server-side method call without risking the client impersonating the session id.


#4

I was going to mess around with a fun experiment where anonymous (i.e. not logged in) users could visit a web page and enter text, which is saved in a database, but once they leave the site, their DB documents are wiped out. I suppose instead of using Meteor’s connection object, I could just have the client generate a random hash and use that to insert documents.


#5

Another way to approach that is to just auto-login users for their session and then delete the user accounts when they log out. Then you can use all the goodies of Accounts instead of rolling your own.


#6

*Meteor.connection._lastSessionId


#7

I know this is a super old thread, but for an experiment I would like to get hold of the sessionId on the client, but I can’t seem to manage how to do it. When I register a DDP.onReconnect handler, it prints out the connection Object, which contains _lastSessionId, but when I try to access it is is alway null. What am I doing wrong?

DDP.onReconnect(function(connection){
	console.log(`DDP.onReconnect`, connection, connection._lastSessionId);
});

#8

I normally just use Meteor.connection._lastSessionId.


#9

@robfallows thanks for responding. I tried Meteor.connection._lastSessionId first, but it is null. At what stage in bootstrapping the app does it become set? When I attach it to an event handler like a button click, I can see the value, but in autorun or Meteor.startup it is null.


#10

I managed to get it to work like this, but it seems rather hacky

DDP.onReconnect(function(connection){
  console.log(`onReconnect ${connection._lastSessionId}`); // null
  const inter = Meteor.setInterval(function conInt(){
    if(connection._lastSessionId){
      console.log(`interval ${connection._lastSessionId}`); // first interval got the value
      lastSessionId.set(connection._lastSessionId);
      Meteor.clearInterval(inter);
    } else {
      console.log(`running interval`)
    }
  },50);
});