Vue.js

vue.js | How to implement route guard

This becomes very crucial when you are developing an application that has registration and user login features. I was recently developing an application vue.js and I came to this situation to implement route authentication or guard.

Vue Router has few Navigation guards to help us here, that you can use as a hook before every route. We write the Navigation Guard as a straightforward function that people can easily understand and use.

Have a look at the below example.

Vue.js Route Guard : Write a common function in for checking if the user is authenticated.

function guardMyroute(to, from, next)
{
var isAuthenticated= false;
if(localStorage.getItem('LoggedUser'))
isAuthenticated = true;
else
isAuthenticated= false;if(isAuthenticated) {
next(); // allow to enter route
} else{
next('/login'); // go to '/login';
}
}

The above function verifies whether a user is authenticated. We set the local storage item with the key “LoggedUser” when a user utilizes the login form and successfully logs into the system.

Vue.js Route Guard : Who sets the Localstorage item?

This is very important. In most cases, it would be a Login component which calls a web API or by any other means to check if the provided credentials are valid and then sets this localstorage key as an indicator for whether the user is an authenticated one or not. In my example, the Login component sets the below after validating the credentials of a user.

Let us assume the userlogin validation API call returns the below response

So I would set the local storage to something like below

localStorage.setItem('LoggedUser',results.User);

Vue.js Route Guard: Let’s now look at my router.

import Vue from "vue";
import Router from "vue-router";
import Login from "./views/Login.vue";Vue.use(Router);export default new Router({
routes: [
{
path: "/",
name: "home",
component: Login,
meta: {title: 'Home'}
},
{
path: "/login",
name: "login",
component: Login,
meta: {title: 'Login'}
},
{
path: "/dashboard",
name: "dashboard",
meta: {title: 'Dashboard'},
component: Dashboard,
}
]
});

It’s quite simple. it’s now time to apply our function to the router guard.

Let’s hook the above function to the above router definition now. So the code would be like below

import Vue from "vue";
import Router from "vue-router";
import Login from "./views/Login.vue";Vue.use(Router);function guardMyroute(to, from, next)
{
 var isAuthenticated= false;
//this is just an example. You will have to find a better or 
// centralised way to handle you localstorage data handling 
if(localStorage.getItem('LoggedUser'))
  isAuthenticated = true;
 else
  isAuthenticated= false; if(isAuthenticated) 
 {
  next(); // allow to enter route
 } 
 else
 {
  next('/login'); // go to '/login';
 }
}export default new Router({
  routes: [
    {
      path: "/",
      name: "home",
      beforeEnter : guardMyroute,
      component: Login,
      meta: {title: 'Home'}
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {title: 'Login'}
    },
    {
      path: "/dashboard",
      name: "dashboard",
      beforeEnter : guardMyroute,
      meta: {title: 'Dashboard'},
      component: Dashboard,
    }
  ]
});

Take a look at the new router definitions and then observe how we define an additional guard on each router. We have connected these guards to our function named “guardMyRoute.” The guard’s name is “beforeEnter”.

Whenever this route is triggered, it automatically activates the route guard function, thus aiding us in authenticating our routes.

Having said that there some guards that vuejs have in its pocket to help us with various needs. Below is some information on them

Route Guards are
beforeEnter: action before entering a specific route (unlike global guards, this has access to this) (this is what we have used in our above example)

The Global Guards are :
beforeEach: action before entering any route (cannot have access to this scope)
beforeResolve: action before the navigation is confirmed, but after in-component guards (same as beforeEach with this scope access)
afterEach: action after the route resolves (you cannot affect the navigation)

The Component Guards would be :
beforeRouteEnter: action before navigation is confirmed, and before component creation (no access to this scope)
beforeRouteUpdate: action after a new route has been called that uses the same component
beforeRouteLeave: action before leaving a route

hope it’s simple. Enjoy programming

You can read the same article on my medium blog here.

You can buy me a coffee , if you like.

Leave a Reply

Your email address will not be published. Required fields are marked *