fixed tracker.autorun login redirect problem

After having an unknown redirect if logged in bug for a week or so (well actually realizing it for a week, but it’s been there since beginning), I finally realized how to fix it.

I had the following code:

tracker.autorun(function() {
var user = Meteor.user();
if (user) {
FlowRouter.go(‘search’);
// make bootstrap modal backdrop go away, in case system login too slow and user attempt to login
$(‘body’).removeClass(‘modal-open’);
$(‘.modal-backdrop’).remove();
}
else {
BlazeLayout.render(‘Home’);
}})

Others have used onLogin to trigger the redirect, but I felt like that was an inferior option, since if the user already logged in, he can still go to home page and perform more login (which will fail of course).

Turned out, that code will run everytime the current user is updated!! I didn’t expect that but that’s how autorun works … run it everytime meteor.user() gets updated. I guess that’s pretty smart actually.

So this code works fine, except when the user goes home, gets auto logged in, and this autorun will rerun everytime user get update, so after every profile update, the user is redirected to search page!! terrible UX!!

Turned out the fix is super simple, I have to stop the autorun after the user has already been redirected:

var handle = tracker.autorun(function() {
var user = Meteor.user();
if (user) {

handle.stop()
}

}

Glad to understand Meteor tracker another bit better from this bug!

Leave a Reply

Your email address will not be published. Required fields are marked *