Blog>
Snippets

Route Guards for Authentication in Vue.js 3 SPA

Using Vue Router's navigation guards to protect routes that require authentication, redirecting unauthenticated users to a login page.
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import Login from './components/Login.vue';
import Dashboard from './components/Dashboard.vue';

// Function to simulate checking if the user is authenticated
function isAuthenticated() {
  // Here you would check the user's session
  return localStorage.getItem('isAuthenticated') === 'true';
}

// Create a Vue Router instance
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'Home', component: Home },
    { path: '/login', name: 'Login', component: Login },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard,
      meta: { requiresAuth: true }
    }
  ]
});

// Global before guard to check for authentication on routes that require it
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated()) {
      next({ name: 'Login' });
    } else {
      next();
    }
  } else {
    next(); // ensure to always call next()! Otherwise the hook will not be resolved
  }
});

export default router;
This code snippet defines a simple function 'isAuthenticated()' to simulate authentication check. It then creates a new Vue Router instance specifying routes, including a protected '/dashboard' route. A global navigation guard 'beforeEach' is added to the router to intercept navigation to routes that require authentication. If the user attempts to navigate to a guarded route and is not authenticated, they are redirected to the '/login' route.