Vue Router Protected Routes With Navigation Guards


By onjsdev

If you want to prevent the user from navigating on routes that the user doesn't have permission to navigate, you must protect these routes. In this article we will build a route protection mechanism for unauthenticated users in a vue application.

For the sake of simplicity, however, we don't have an authentication system so if the isAuthenticated key have been assigned true in localStorage, we will accept the user as authenticated.

Setting Routes With Vue Router

First step in this guide is setting routes. We will have two routes, home and dashboard. We will implement a guard on Dashboard route so that dashboard route will be protected.

import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('../views/DashboardView.vue'),
    },
  ],
});

export default router;

Global Navigation Guard To Protected Routes

We can configure a guard in two ways in a vue js application, globally and locally. In this step, we will set a global navigation guard with the help of beforeEach method from vu-router.

router.beforeEach((to, from, next) => {
  if (to.name === 'dashboard' && !localStorage.getItem('isAuthenticated'))
  // Redirect the home page
    next({ name: 'home' });
  else next();
});

Local (Per Route) Vue Router Navigation Guard

The other way is to set up a local navigation guard for that route where the route itself is set. Let's see how to proctect the dashboard route as locally.

{
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('../views/DashboardView.vue'),
    beforeEnter: (to, from) => {
      if (!localStorage.getItem('isAuthenticated')) {
        // Redirect the home page
        return { name: 'home' };
      }
        return true;
    },
},

Conclusion

That's all. In this article, we have created a navigation guard using vue-router to protect the dashboard route. After implementing the navigation guard for your app, you can test it by setting isAuthenticated item in localStorage and attempting navigate the dashboard page.

Thank you for reading.