- I want to redirect users to a login page and then back to the originally requested page after a successful login/signup.
- Examples I have found don’t work (or I am not able to get them to work)
- I am using Accounts.onLogin (which does not appear to work as documented.)
How can I redirect a user back to the originally requested page?
Below are the primary relevant code snippets. Please see this repo for a complete example of the issue: https://github.com/andersr/meteor-accounts-login-test
Route and before hook
function redirectIfAnonymous(context, redirect) {
const notSignedIn = Meteor.userId() === null
if (notSignedIn) {
Session.set("loginRedirect", true)
Session.set("requestedPage", context.path)
alert("Please sign in to continue.")
redirect('login')
}
}
FlowRouter.route('/restricted', {
name: 'restricted',
triggersEnter: [redirectIfAnonymous],
action() {
mount(MainLayout, {
content: () => <Restricted />
})
}
})
Accounts.onLogin (where the redirect is handled)
Accounts.onLogin(function(){
if (Meteor.isClient) {
const
route = FlowRouter.current().route.name,
didLoginOrSignup = route === "login" || route === "signup" ,
wasRedirected = Session.get("loginRedirect"),
requestedPage = Session.get("requestedPage")
if(wasRedirected && didLoginOrSignup){
//FlowRouter does *not* redirect to this route, even through the above conditions return true
FlowRouter.go(requestedPage)
Session.set("loginRedirect", false)
}
//Instead FlowRouter redirects to the homepage, even though no such call has been made
}
})