Implement Route Guard in vue.js

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. Navigation Guard is written as a plain function that can be understood and used easily

Have a look at the below example.

Write a common function to check 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 checks if a user is authenticated or not. The local storage item with key “LoggedUser” is set when a user uses the login form and logs in successfully to the system.

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);

Lets 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 . its 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,

}

]

});

Have a look at the new router definitions and then you can see an additional guard being defined on each router. These guards are hooked to our function named “guardMyroute”. The guard name is “beforeEnter”.

So what happens is any time this route is triggered it automatically fires the route guard function and thus helps us to authenticate 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