Search code examples
javascriptmeteoriron-router

Meteor / Iron Router external redirection


So I'm creating a basic vanity URL system, where I can have http://myURL.com/v/some-text, grab an item from the database and redirect to a specific URL based on whether or not the client is mobile/desktop and other features.

I usually build Facebook apps, so in the case of desktop they would be redirected to a Facebook URL, otherwise on mobile I can just use normal routes.

Is there a way to redirect from Iron Router on the server-side to an external website?

this.route('vanity',{
    path: '/v/:vanity',
    data: function(){
        var vanity = Vanity.findOne({slug:this.params.vanity});

        // mobile / desktop detection

        if(vanity){
            if(mobile){
                // Redirect to vanity mobile link
            }else{
                // Redirect to vanity desktop link
            }
        }else{
            Router.go('/');
        }
    }
});

Solution

  • Here is a simple 302-based redirect using a server-side route:

    Router.route('/google/:search', {where: 'server'}).get(function() {
      this.response.writeHead(302, {
        'Location': "https://www.google.com/#q=" + this.params.search
      });
      this.response.end();
    });
    

    If you navigate to http://localhost:3000/google/dogs, you should be redirected to https://www.google.com/#q=dogs.

    Note that if you would like to respond with a 302 to all request verbs (GET, POST, PUT, HEAD, etc.) you can write it like this:

    Router.route('/google/:search', function() {
      this.response.writeHead(302, {
        'Location': "https://www.google.com/#q=" + this.params.search
      });
      this.response.end();
    }, {where: 'server'});
    

    This may be what you want if you are doing redirects for SEO purposes.