How can I redirect back to the originally requested page after login using FlowRouter?

  • 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:

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.")

FlowRouter.route('/restricted', {
  name: 'restricted',
  triggersEnter: [redirectIfAnonymous],
  action() {
    mount(MainLayout, {
      content: () => <Restricted />

Accounts.onLogin (where the redirect is handled)


   if (Meteor.isClient) {
	route = FlowRouter.current(),
	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
        Session.set("loginRedirect", false)
       //Instead FlowRouter redirects to the homepage, even though no such call has been made

I recommend using the useraccounts package, it does this automatically:

Do you mind pointing to the part of the documentation where it mentions that? I bent over backwards to make this happen on my site, but resorted to Accounts.onLogin hook

Setup of the package is somewhat counter-intuitive and not really well-documented IMHO.

I only got it working as expected when I followed these rules:

  1. Work with AccountsTemplates.ensureLogin on the routes (in FlowRouter using triggersEnter)
  2. Setup special routes for signIn, signUp etc. with AccountsTemplates.configureRoute()

Ok, thanks for the response. So useraccounts package doesn’t really do this automatically then. I am using the package (albeit still with iron-router) and needed to solve the same problem.

It does it automatically, but only if you add the ensureLogin trigger to all routes and setup the sign-in route right.

Ah, thanks. I guess that is the part I wasn’t able to figure out myself :slight_smile:

1 Like

You’re welcome. Please also note that it’s important to setup the ‘signUp’ route as well. Otherwise, the package behaves a bit awkward. In my app, I additionally set-up the ‘forgotPwd’ and ‘resetPwd’ routes.