Onjsdev

Share


Vue Router Protected Routes With Navigation Guards


By onjsdev

Dec 13th, 2023

If you want to prevent users from navigating on routes for which they don't have permission, such as unauthenticated users, you must protect these routes. In this article, we will build a route mechanism to protect certain routes in a Vue application.

Note that for the sake of simplicity, we don't have a fully implemented authentication system. However, if the "isAuthenticated" key has been assigned the value "true" in localStorage, we will treat this as a permission and accept the user as authenticated.

Let's get started.

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 vuejs application, globally and locally. In this step, we will set a global navigation guard with the help of beforeEach method from vue-router.

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

In this globally guard mechanism:

  • The guard checks if the user is trying to navigate to the route named dashboard.
  • If the user is not authenticated (checked using localStorage.getItem('isAuthenticated')), it redirects them to the route named home.
  • Otherwise, the navigation continues normally by calling 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 protect 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;
    },
},

In this example, beforeEnter is a route-specific navigation guard. It allows you to define custom logic that will be executed before the component is loaded.

In this local guard:

  • The beforeEnter guard checks if the user is authenticated (similar to the global guard example).
  • If the user is not authenticated, it redirects them to the route named home.
  • Otherwise, it allows the navigation to continue and returns 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.