Search code examples
javascriptmeteoriron-router

Redirection with iron-router and onBeforeAction on meteor app


I have a meteor app and with the package iron-router, I try to block all pages if the user is not connected except fews pages. And if nothing is specified we go on the landing page. So in the file router.js, I have :

Router.onBeforeAction(function() {
    if (!Meteor.userId()) { 
        Router.go('login');
    } else {
    this.next();
    }
}, {
except: [
    "login", "landing", "register", "forgotPassword" 
]
});

Router.route('/', function () {
    Router.go('landing');
});

But when I go on localhost:3000/ I'm redirected to login page and not to the landing page.

If I remove the onBeforeAction function, I'm redirect to the landing page. So it must be a problem with this 2 functions but I don't know where. Maybe I need to precise the "/" in the exceptions but it doesn't work. Do you have an idea ?


Solution

  • You need to define the route '/' in your exceptions too, otherwise this is caught by the onBeforeAction

    Try re-defining as follows

    Router.onBeforeAction(function() {
        if (!Meteor.userId()) { 
            Router.go('login');
        } else {
        this.next();
        }
    }, {
    except: [
        "default", "login", "landing", "register", "forgotPassword" 
    ]
    });
    
    Router.route('/', function () {
        Router.go('landing');
    }, { 
        name: "default"
    } );
    

    In this case you name the route and then you can add it to your exception list

    see http://iron-meteor.github.io/iron-router/#named-routes