FlowRouter redirect if user is logged in and if path is

I’m using Meteor with FlowRouter and i’m looking for a condition like this:

My current Routes:

        Accounts.onLogin(function(){
            FlowRouter.go('clients');
        });
        Accounts.onLogout(function(){
            FlowRouter.go('home')
        });

        FlowRouter.triggers.enter([function(context, redirect){
            if(!Meteor.userId()){
                FlowRouter.go('home')
            }
        }]);


        FlowRouter.route('/', {
            name: 'home',   
            action(){
                BlazeLayout.render('HomeLayout');
            }
        });
        FlowRouter.route('/clients',{
            name: 'clients',
            action(){
                BlazeLayout.render('MainLayout', {main: 'Clients'});
            }
        });

You could try something like this

function isNotLoggedIn(context, redirect) {
    if (!Meteor.user() && !Meteor.loggingIn()) {
        redirect('/login');
    }
}

function isLoggedIn(context, redirect) {
    if (Meteor.user() || Meteor.loggingIn()) {
        redirect('/clients');
    }
}

// Check if user is logged in an redirect to /login
FlowRouter.triggers.enter([isNotLoggedIn], {
    except: ['login']
});

// Check if user is logged in an redirect to /clients
FlowRouter.triggers.enter([isLoggedIn], {
    only: ['login']
});
2 Likes

That works. Thanks!
I have this question on StackOverflow also, if u want to answer it.

Just be careful with that solution if your users are ever likely to use bookmarks (or any link from outside of your app). I found I couldn’t access the current user from triggers.enter even though they had logged in previously. I raised an issue on the Flow Router repo but got no response.

tl;dr: Book mark the route you expect to redirect and then load from the bookmark to see if it still works for you.

You could always add

Tracker.autorun(function () {
   if(!Meteor.userId()) {
     FlowRouter.go('login');
   }
 });

Nah, it doesn’t solve this particular problem. They are logged in already. It’s just navigating from a bookmark or external link causes the app to reload and Meteor.user() isn’t returning anything at the time the FlowRouter.triggers.enter() runs. It is available when any internal link is clicked.

This was about 6 months ago so maybe they could have fixed it in the mean time.

I tested and there is no problem with bookmarking.

1 Like