title: vuejs - Redirect from login/register to home if already loggedin, Redirect from other pages to login if not loggedin in vue-router
body: <p>I want to redirect user to home page if logged-in and wants to access login/register page and redirect user to login page if not logged-in and wants to access other pages. Some pages are excluded that means there is no need to be logged in so my code is right below:</p>
  
  <pre><code>router.beforeEach((to, from, next) =&gt; {
      if(
          to.name == 'About' ||
          to.name == 'ContactUs' ||
          to.name == 'Terms'
      )
      {
          next();
      }
      else
      {
          axios.get('/already-loggedin')
              .then(response =&gt; {
                  // response.data is true or false
                  if(response.data)
                  {
                      if(to.name == 'Login' || to.name == 'Register')
                      {
                          next({name: 'Home'});
                      }
                      else
                      {
                          next();
                      }
                  }
                  else
                  {
                      next({name: 'Login'});
                  }
              })
              .catch(error =&gt; {
                  // console.log(error);
              });
      }
  });
  </code></pre>
  
  <p>But the problem is that it gets into an infinite loop and for example each time login page loads and user not logged-in, it redirects user to login page and again to login page and...</p>
  
  <p>How can I fix this?</p>