Sergio
Sergio

Reputation: 822

Vue Router Guards are not Blocking Guarded Routes When Typed in Address Bar

I have a simple vue app that I am trying to protect some routes, Ie.: if user is logged in show the dashboard page and block the member-login page. If the user is NOT logged in show the member-login page but block the dashboard page.

It is working on the navigation... so if I am not logged in and click "dashboard" I get redirected to the member-login page. And if I am logged in and click "login" I get redirected to the dashboard page. Cool.

Except if I type the path in the address bar, meaning, if I am logged in and click "login" I get redirected to the dashboard, but if I type /member-login in the address bar it still takes me to the member-login page, and it shouldn't. Same in reverse with the dashboard page if I am not logged in.

I am using the beforeEach() method to perform the guards, and here is what I have:

router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));
   if(ls === null && to.name === 'dashboard'){ 
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') { 
      next('/dashboard');
   } else {
      next();
   }
});

I should mention that this is a global guard, and it lives in the main.js file of my project.

What am I missing?

Thanks so much!

Upvotes: 0

Views: 1137

Answers (2)

Sergio
Sergio

Reputation: 822

So, the issue was a stupid mistake on my part...

I had the router.beforeEach method below the new Vue({}) method and it didn't like that. So moving the beforeEach method above the new Vue method fixed this issue.

Buggy:

new Vue({
   el: '#app',
   router,
   store,
   components: { App },
   template: '<App/>'
});

router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));

   if(ls === null && to.name === 'dashboard'){
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') {
      next('/dashboard');
   } else {
      next();
   }
});

Fixed:

router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));

   if(ls === null && to.name === 'dashboard'){
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') {
      next('/dashboard');
   } else {
      next();
   }
});

/* eslint-disable no-new */
new Vue({
   el: '#app',
   router,
   store,
   components: { App },
   template: '<App/>'
});

Upvotes: 1

Jerry
Jerry

Reputation: 168

You mean you input the /member-login and it takes you to the login page ? It seems to me that it's the right action , or there's some misunderstanding I get? Can you provide more details ?

Upvotes: 0

Related Questions