Search code examples
javascriptmeteoriron-router

Doing something different for main route in meteor iron router


Im using Iron-Route for routing in my meteor app. As I have multiple modules and I want to avoid multiple coding, I put the filter for authentification (role) to the core package:

core package

var filters = {
    authenticate: function () {
        var user;
        if (Meteor.loggingIn()) {
            this.layout('login');
            this.render('loading');
        } else {
            user = Meteor.user();
            if (!user) {
                this.layout('login');
                this.render('signin');
                return;
            }
            this.layout('StandardLayout');
            this.next();
        }
    }
}
Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    before: filters.authenticate
});
Router.route('/', function () {
    this.render('contentTemplate', { to: 'content' });
    this.render('navigationTemplate', { to: 'navigation' },)
});

other packages

...just need this:

Router.route('/article/:_id', {
    name: 'article',
    yieldTemplates: {
        'navigationPage':   { to: 'navigation' },
        'contentPage':      { to: 'content' } 
    }
});

Now there is a check on every module (route) before displaying anything. But I need an exception for the front page. The main page Route.route('/') should be accessed also by user who are not logged in. How do I do that?


Solution

  • You can use the onBeforeAction hook from iron:router as shown below. This solution assumes your login route is named 'login' . But can be modified to fit your needs.

    ./client/lib/hoooks/router.js

    Router.onBeforeAction(function () {
        // all properties available in the route function
        // are also available here such as this.params
        if  (!Meteor.userId()) {
            //code for action to be taken when user is not logged in
            this.redirect('login');
            this.stop();
        } else {
            this.next();
        }
    },{except: ['homeRouteName'] });
    

    NB: Replace 'homeRouteName' with the name of your route at '/'