Introduction:
We looked at adding routing and performing standard routing operations in our Vue js application in the last post. We will learn about RouteGuard in Vue JS in this tutorial. You can check the previous post by clicking here.
In order to assist us, Vue Router offers a couple of navigation guards that you can use as a hook before each route. The function Navigation Guard is designed in a straightforward manner to make it simple to read and use.
Get Started:
Step 1: Common function for checking Authentication.
First of all, we need a common function to check whether the existing user has authenticated user or not.
function chechAuthGuard(to, from, next) { var isAuthenticated = false; if (localStorage.getItem('userData')) isAuthenticated = true; else isAuthenticated = false; if (isAuthenticated) { next(); // allow to route } else { next('/signin'); // go to '/signin'; } }
The aforementioned function examines a user’s authentication status. When a user successfully signs in to the system using the login form, the local storage object with the key “userData” is set.
Step 2: Set up the common router.
Here, I just copy-paste the common router from my previous post.
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../components/Home.vue' import About from '../components/About.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/About', name: 'About', component: About } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
Step 3: Add our common method to the router.
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../components/Home.vue' import About from '../components/About.vue' Vue.use(VueRouter) function chechAuthGuard(to, from, next) { var isAuthenticated = false; if (localStorage.getItem('userData')) isAuthenticated = true; else isAuthenticated = false; if (isAuthenticated) { next(); // allow to route } else { next('/signin'); // go to '/signin'; } } const routes = [ { path: '/', name: 'Home', component: Home, beforeEnter : chechAuthGuard, }, { path: '/About', name: 'About', component: About, beforeEnter : chechAuthGuard, } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
Look at the updated router definitions, and you’ll notice that each router now has a second guard defined. These guards are connected to our chechAuthGuard function. beforeEnter is the name of the guard.
As a result, whenever this route is activated, the route guard function is immediately fired, which aids with route authentication.