Reputation: 57
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
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:
/login
/login
and then redirects to /greetings
on successUpvotes: 4