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 :
Redirect request from 'onResponse' to another domain and not to change the handler function.
Server method that can allow me to configure all of the routes configuration and inject the proxy redirection on that.
Thanks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With