How to get Meteor.user() to return on the server side?

You have to use Meteor.user() in a place where a request is made from the client (such as a Meteor.methods or a Meteor.publish).

It can’t be placed anywhere else because meteor wouldn’t know at that point in the code the user is supposed to bound to. If there is a place a request of some form is made from the client it can do this:

In a Meteor.publish:

Meteor.publish("collection", function() {
    //returns undefined if not logged in so check if logged in first
    if(this.userId) {
        var user = Meteor.users.findOne(this.userId);
        //var user is the same info as would be given in Meteor.user();
    }
});

In a Meteor.methods:

Meteor.methods({
    "test":function() {
        //should print the user details if logged in, undefined otherwise.
        console.log(Meteor.user());
    }
}

To use Meteor.user() on a server side route:

You need Meteor router installed as a package via meteorite to allow you to have a server rendered page. (installed via mrt install router)

A server side route could then handle the web request:

 Meteor.Router.add('/awebpage', function(id) {
     var userId = this.params.userid;
     var logintoken = this.params.logintoken;
     var isdirect = this.param.direct;
     var user = Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
     if(user) {
         //the user is successfully logged in

         return "You, "+user.profile.name+", are logged in!";
     }
     else
     {
         if(isdirect) {
             return "<h3>Loading</h3><script>window.location.href="https://stackoverflow.com/awebpage?direct=true&userid="+localStorage.getItem("Meteor.userId") +"&logintoken="+localStorage.getItem("Meteor.loginToken")</script>";
         }
         else
         {
             return "Not logged in"
         }
     }
 });

So now when you visit /awebpage it would check whether the user is logged in and do the thing you want when they are logged in. Initially there is a redirect to relay the data from localstorage back to the URI.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)