How to redirect after user has just logged in or just logged out

lleonard188 picture lleonard188 · Apr 6, 2014 · Viewed 7.4k times · Source

It seems Deps.autorun is the way to go but Router.go doesn't seem to work within Deps.autorun.

Answer

David Weldon picture David Weldon · Apr 6, 2014

Here is an example with three routes: index, signin and dashboard:

Router.configure({layoutTemplate: 'layout'});

Router.map(function() {
  this.route('index', {path: '/'});
  this.route('signin');
  this.route('dashboard');
});

var mustBeSignedIn = function(pause) {
  if (!(Meteor.user() || Meteor.loggingIn())) {
    Router.go('signin');
  } else {
    this.next();
  }
};

var goToDashboard = function(pause) {
  if (Meteor.user()) {
    Router.go('dashboard');
  } else {
    this.next();
  }
};

Router.onBeforeAction(mustBeSignedIn, {except: ['signin']});
Router.onBeforeAction(goToDashboard, {only: ['index']});

If a user is on the index page and she is logged in, she will automatically be routed to the dashboard page. On any page except for signin, if the user is not logged in she will be routed to the signin page. onBeforeAction is reactive so these rules will be enforced immediately if the user logs in or out.

Of course your routes will be different, but hopefully this example illustrates one way to make this work with iron-router.

Also see the using hooks section of the iron-router guide.