brunoid
brunoid

Reputation: 2201

Meteor: Redirect to another url

Is it possible to send a redirect from server side to client in Meteor framework.

I can't find out this functionality.

Is so, could you please show an example.

Upvotes: 0

Views: 949

Answers (1)

Ser
Ser

Reputation: 2870

There are two ways to communicate between your client side and your server side:

  • Collections
  • Meteor.methods

Let's assume you have:
- FlowRouter
- Blaze
- FlowRouter Blaze
- autopublish

Using collections

You can do the following:
Collection file /collections/Events.js:

// Create a global collection 
Events = new Meteor.Collection("Events");

Somewhere on the server side:

Events.insert({
    type: 'redirect',
    route: 'home'
    // require user_id if you want this to work with multi users
    params: {}
});

Client side route:

FlowRouter.router('/some/url', {
     action: function () {
          BlazeLayout.render('Layout', {main: 'displayedTemplate'});
     },
     name: 'home'
});

Client side layout:

Template.Layout.onCreated(function () {
    // suscriptions to Events if autopublish have been removed...?
    this.autorun(function() {
        const event = Events.findOne();
        switch (event.type) {
            case 'redirect':
               FlowRouter.go(event.route, event.param);
               Events.delete(event);
            ...
        }
    });
});

Using methods

When the user does something and you want to redirect him:

 Template.Layout.events({
    'click h2': function (event, template) {
        Meteor.call('getCoffee', function (err, event) {
            if (err) {
               //handle error
            } else {
                if (event.type === 'redirect') {
                     FlowRouter.go(event.route, event.param);
                }
            }
        });
    }
})

Upvotes: 1

Related Questions