How can I identify each user in a meteor app?

Hello,

I need a way to identify each user in my meteor app, even the ones that have not logged in yet or do not have an account.

I assume there is some kind of id (maybe for the socket connection) that meteor uses internally to know where to send the responses from the server.

I need to cache the response from an “expensive” meteor method per user.

Thanks

Maybe something like this DDP._CurrentInvocation.get().connection.id ?
How do I get the connection id?

I discovered the Meteor.onConnection handler for this. On the server you do the following and end up with a collection you can query about active connections. You can even subscribe to the collection on the client …

export const Connections = new Mongo.Collection("connections");

Meteor.onConnection(function (connection) {
  const connectionId = connection.id;
  console.log(`Meteor.onConnection inserted ${Connections.insert({ _id: connectionId, connection: connection })}`);

  connection.onClose(function () {
    let c = Connections.remove(connectionId);
    console.log(`onClose ${connectionId} removed ${c}`);
  });
});
Meteor.publish('connections', function () {
  const publication = this;
  var c = Connections.findOne(publication.connection.id);
  if (!c) {
    console.log(`Connection inserted ${Connections.insert({ _id: publication.connection.id})}`);
  }
  //
  // publish connections for this id (should be only one)
  //
  return Connections.find({ _id: publication.connection.id });
});

Meteor.startup(function () {
  //
  // clear Connections collection when server starts
  //
  Connections.remove({});
});
1 Like