hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Please how can I safely redirect inside the onRequest lifecycle

Open Akumzy opened this issue 5 years ago • 2 comments

Support plan

  • is this issue currently blocking your project? (no):
  • is this issue affecting a production system? (no):

Context

  • node version: v15.4.0
  • module version:
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): hapi application
  • any other relevant information:

How can we help?

Please how can I safely redirect inside the onRequest lifecycle?

server.ext('onRequest', function (req, h) {
  if (routes.includes(req.path)) {
    // This is causing an error
    h.redirect('/login')
  }
  return h.continue
})

Akumzy avatar Dec 30 '20 23:12 Akumzy

Give something like this a try:

    server.ext('onRequest', (request, h) => {

        const routes = ['/login2'];
        if (routes.includes(request.path)) {
            return h.redirect('/login').code(301).takeover();
        }

        return h.continue;
    });

    server.route({
        method: 'GET',
        path: '/login',
        handler(request, h) {

            return { body: 'This is the /login route' };
        }
    });

devinstewart avatar Dec 31 '20 00:12 devinstewart

Thank you so much @devinstewart

Akumzy avatar Dec 31 '20 09:12 Akumzy