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:
router.beforeEach((to, from, next) => {
if(
to.name == 'About' ||
to.name == 'ContactUs' ||
to.name == 'Terms'
)
{
next();
}
else
{
axios.get('/already-loggedin')
.then(response => {
// 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 => {
// console.log(error);
});
}
});
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...
How can I fix this?
If someone is still looking for an answer, you can reverse the logic. So, the same way you have requiresAuth, you will have hidden routes for authenticated users. (example with firebase)
And in your beforeEeach
Here's what I'm doing. First I'm using a
meta
data for the routes, so I don't need to manually put all routes that are not requiring login:Then, I have a global guard like this:
Here I am storing if the user is logged in or not, and not making a new request.
In your example, you have forgotten to include
Login
into the list of pages that "don't need authentication". So if the user is trying to go to let's sayDashboard
, you make the request, turns out he's not logged in. Then he goes toLogin
, BUT your code checks, sees it's not part of the 3 "auth not required" list, and makes another call :)Therefore skipping this "list" is crucial! ;)
Good luck!