meteor

How to get logged-in user email in publish functions in meteor?


I've created a meteor 0.5.4 app - added accounts-ui, accounts-password, and added {{loginButtons}} to the template name="hello" block hat comes stock with every meteor create.

When I type this in a chrome browser console, Meteor.user().emails[0].address as per these SO sources - Access user email address in Meteor JS app, Meteor Querying other users by email - I get the currently logged in users email.

When I attempt to put the same code within the if (Meteor.isClient) section :

Template.hello.greeting = function () {
   return Meteor.user().emails[0].address;
};

I get :

 Uncaught TypeError: Cannot read property '0' of undefined foo.js:3
 Exception from Meteor.flush: TypeError: Cannot call method 'firstNode' of undefined

If you can't place Meteor.user() within publish functions, how else can I get the email of the logged in user? I've tried making it a shared function, and calling it within the client side function with Meteor.call('getEmail', Meteor.userId()) with similar results.


Solution

  • Templates are reactive. That means that when the page loads, the template is run, and it will be run again when its dependent data source changes. In your case, the first time it runs, Meteor.user() isn't ready yet, so it has no emails attribute yet, which causes an error. To fix this you need to check whether the user object exists yet:

    Template.hello.greeting = function() {
      var user = Meteor.user();
      if (user && user.emails)
        return user.emails[0].address;
    }
    

    To get the current user inside a publish function, use this.userId.