Meteor.user() returns undefined after page reload
Asked Answered
F

1

7

Thing is I want to check if the user is is logged in via Meteor.user() within onBeforeAction in my routes. Problem is, after a page reload Meteor.user() returns undefined for a split second before it gets loaded.

Here my route config:

Router.map(function() {
    this.route('list', {
        path: '/list',
        template: 'list',
        onBeforeAction: function(){
            console.log('onBeforeAction');
            if(!Meteor.user()){
                 Router.go('/login');
            }
            this.next();
        }
    });
});

I googled a lot and the workarounds with "waitOn" and "return Meteor.user();" doesn't seem to work in my case. Also interesting...locally it works perfectly fine, so I can do a page reload and still stay on the "list" view, but the on Modulus deployed app acts as described above and redirects to the login page.

Any ideas? Thanks in advance.

Fluviomarine answered 15/8, 2015 at 12:52 Comment(0)
B
7

It's better to use !!Meteor.userId() to check if a user is logged in, because there's no latency while waiting for the user data to be loaded from the server. In fact, Meteor.user routine is more or less equivalent to:

function () {
  return Meteor.users.findOne({ _id: Meteor.userId() });
}

which explains why it may return undefined even if the user is logged in.

Brunner answered 15/8, 2015 at 12:59 Comment(2)
Is there any difference between if (Meteor.userId()) and if (!!Meteor.userId())?Diathermic
@Acute No there is not any difference between these twoTincher

© 2022 - 2024 — McMap. All rights reserved.