Search code examples
vue.jsvuejs3vuexvue-router

How to protect routes in vuejs using vuex


How can I protect the routes globally instead of using this, this works on default and redirects users without token to login

 beforeRouteEnter(to, from, next) {
    const hasToken = localStorage.getItem('token');
    if (!hasToken) {
      next('/login'); // Redirect to the login page
    } else {
      next();
    }
  },

This is my how I get my token

 created() {
    this.getTokenFromStorage();
  },
 computed: {
    ...mapGetters(['currentUser', 'error', 'getToken']),
  },
methods: {
    ...mapActions(['getUser', 'getTokenFromStorage']),
  },

I get the token in my Vuex store enter image description here

How can I just use my getToken and access it globally in Vue


Solution

  • For that you can use Navigation Guards in Vue Router. Here's the documentation link.

    const router = createRouter({ ... });
    
    // use `beforeEach` navigation guard on router
    router.beforeEach((to, from) => {
      const hasToken = localStorage.getItem('token');
    
      if (!hasToken) {
        return '/login'; // Redirect to the login page
      }
    });