Vue JS

# Route Authentication using Vue-router

Route Authentication means that in our application we want to define access permissions for certain routes. The most common use case is that a website has certain routes that you can only access after you have completed the login flow and have a valid auth_token for your session after login.

This means that we have to prevent user from directly visiting routes or webpages in our application which require you to login first.

Let's have a view Login which contains the login form and all the logic related to login flow. If login is success we store the auth_token which we get from the backend in the localStorage so that we can access it from anywhere and validate if user is logged in or not.

A second view Dashboard which is at route /dashboard and can only be accessed if user is logged in and has auth_token set in localStorage.

Things we need to take care of:

  1. We can access /dashboard only if auth_token is present in localStorage.
  2. If not we will redirect user to login page at /.
  3. If user goes to login route and token is present in localStorage we will redirect to the dasboard as user is already logged in.

So our router.js file will look something like this:

import Vue from 'vue';
import Router from 'vue-router';
import Login from './views/Login.vue';
import Dasboard from './views/Dashboard.vue';

Vue.use(Router);

const router = new Router({

  mode: 'history',
  base: process.env.BASE_URL,

  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    { path: '/dashboard',
      component: Dasboard
    },
  ],
});

export default router;

Now we will add meta data to our routes which will just define which routes are authenticated.

  1. guest - can access without login.
  2. requiresAuth - can access only after login.
import Vue from 'vue';
import Router from 'vue-router';
import Login from './views/Login.vue';
import Dasboard from './views/Dashboard.vue';

Vue.use(Router);

const router = new Router({

  mode: 'history',
  base: process.env.BASE_URL,

  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
      meta: {
        guest: true,
      },
    },
    { path: '/dashboard',
      component: Dasboard,
      meta: {
        requiresAuth: true,
      },
    },
  ],
});

export default router;

Now we will use the beforeEach method from router which allows us to implement custom logic on change of routes in our application. It gives us three parameters to, from & next where :

  1. to - is where the user wishes to go.
  2. from - is where the user is coming from.
  3. next - is a callback function that continues the processing of the user request.
import Vue from 'vue';
import Router from 'vue-router';
import Login from './views/Login.vue';
import Dasboard from './views/Dashboard.vue';

Vue.use(Router);

const router = new Router({

  mode: 'history',
  base: process.env.BASE_URL,

  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
      meta: {
        guest: true,
      },
    },
    { path: '/dashboard',
      component: Dasboard,
      meta: {
        requiresAuth: true,
      },
    },
  ],
});

router.beforeEach((to, from, next) => {
  // if route requires authentication - requiresAuth is true
  if (to.matched.some((record) => record.meta.requiresAuth)) {
      if (localStorage.getItem('auth_token') == null) {
          next({name: 'login'});
      } else {
          next();
      }
  }
  // if route can be accessed without authentication - guest is true 
  // but we redirect back to dashboard if already logged in 
  else if(to.matched.some((record) => record.meta.guest)){
    if (localStorage.getItem('auth_token')) {
        next({name: 'dashboard'});
    } else {
        next();
    }
  }
  // if not guest or requiresAuth continue
  // e.g. about us page 
  else {
      next();
  }
});

export default router;

So we simply wrote three conditions where

  1. If requiresAuth is true we check for auth_token in localStorage, if its null we go back to login else we continue.

  2. Else if guest is true and auth_token is set in localStorage we route to dashboard.

  3. Else we just move forward with the route which doesn't have guest or requiresAuth set to true.

This is just one part of the authentication as you can manually also set auth_token to any value in localStorage and login to the application. So the actual verification happens at the backend to check the validity of the token and according to the response from the backend we can further improve our authentication in the frontend.

If you wish to read further I have another article on how to handle status 401 - Unauthorized in a API.



By Ashish Kanwar Singh

Building products that matter
Senior Software Engineer @XanaduAI

Ashish Kanwar Singh's DEV Profile

Learn More


  • Route Authentication using Vue-router