Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hapi.js redirect from onRequest

I'm using hapi v6.11.1 and have been trying to conditionally redirect oncoming request from my hapi.js server to another server. This is what I've trie so far:

server.on('onRequest',function(request,reply) {

  if(request.headers.customHeader) { // redirect only if header found
    reply('custom header redirection').redirect('http://someurl.com');
    return;
  }

  reply();

});

but the above solution won't work and still hits my server instead the one I specify.

I tried doing reply.proxy() on the 'onRequest' handler and got the following error:

Error: Uncaught error: Cannot proxy if payload is parsed or if output is not stream or data

While trying to figure out a solution, I came across the following from hapi.js docs:

Available only within the handler method and only before one of reply(), reply.file(), reply.view(), reply.close(), reply.proxy(), or reply.redirect() is called.

but the problem is I have around 100 routes and I'll now have to change the handler for each of the request to allow proxying if my condition is met which I don't want to do.

I'll be glad if there's any one of the following is possible :

  1. Redirect request from 'onResponse' to another domain and not to change the handler function.

  2. Server method that can allow me to configure all of the routes configuration and inject the proxy redirection on that.

Thanks.

like image 530
I_Debug_Everything Avatar asked Jul 16 '15 09:07

I_Debug_Everything


1 Answers

Okay so I came up with the following solution:

server.on('onRequest',function(request,reply) {
  if(request.headers.customHeader) {
     request.setUrl('/redirect');
  }
  reply();
});

and then created a route handler that will just proxy the request:

{
    method : '*',
    path : '/redirect',
    config : {
      payload : {
        output : 'stream',
        parse : false,

      },
      handler : function(request,reply) {

        var url = 'https://customUrl.com';
        reply.proxy({'uri' : url, passThrough : true});

      }      
    }
}

In the above, I had to do a setUrl on 'onResponse' because that's the only place I can do that as per the hapijs docs. Secondly I passed on proper values on the '/redirect' to make the proxy redirection work properly.

I'll still wait for someone who can provide me a better solution than this.

like image 197
I_Debug_Everything Avatar answered Sep 19 '22 15:09

I_Debug_Everything