z-hao
z-hao

Reputation: 57

hapi.js - How to redirect to originally requested route after successful authentication?

Is there something like reply.redirect('back') in hapi.js ? I am trying to redirect the user back to the original page they requested before they logged in successfully.

Upvotes: 2

Views: 4150

Answers (1)

Matt Harrison
Matt Harrison

Reputation: 13587

When using the hapi-auth-cookie scheme, there's a handy setting for this exact purpose. Have a look at appendNext in the options.

When you set this to true, the redirect to your login page will contain a query parameter next. next will be equal to the request path of the original request.

You can then use this on successful login to redirect to the desired page. Here's a runnable example that you can play with and modify to your needs:

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({ port: 8080 });

server.register(require('hapi-auth-cookie'), function (err) {

    server.auth.strategy('session', 'cookie', {
        password: 'secret',
        cookie: 'sid-example',
        redirectTo: '/login',
        appendNext: true,      // adds a `next` query value
        isSecure: false
    });
});

server.route([
    {
        method: 'GET',
        path: '/greetings',
        config: {
            auth: 'session',
            handler: function (request, reply) {

                reply('Hello there ' + request.auth.credentials.name);
            }
        }
    },
    {
        method: ['GET', 'POST'],
        path: '/login',
        config: {
            handler: function (request, reply) {

                if (request.method === 'post') {
                    request.auth.session.set({
                        name: 'John Doe'    // for example just let anyone authenticate
                    });

                    return reply.redirect(request.query.next); // perform redirect
                }

                reply('<html><head><title>Login page</title></head><body>' + 
                      '<form method="post"><input type="submit" value="login" /></form>' +
                      '</body></html>');
            },
            auth: {
                mode: 'try',
                strategy: 'session'
            },
            plugins: {
                'hapi-auth-cookie': {
                    redirectTo: false
                }
            }
        }
    }
]);

server.start(function (err) {

    if (err) {
        throw err;
    }

    console.log('Server started!');
});

To test this out:

  • Navigate to http://localhost:8080/greetings in a browser
  • You'll be redirect to /login
  • Click the login button
  • Form posts to /login and then redirects to /greetings on success

Upvotes: 4

Related Questions