QA
Intermediate LevelVue JS

How do you configure Vue Router 4 and implement beforeEach navigation guards for authentication?

❓ Interview Prompt: Explain Vue Router 4 configuration, HTML5 history mode (createWebHistory), and route protection with beforeEach navigation guards.

Vue Router 4 is the official router for Vue 3.

Key Setup Features:

•
'createWebHistory()': Uses HTML5 History API ('/dashboard') for clean URLs without hashes ('/#/dashboard').
•
Global Navigation Guards ('router.beforeEach'): Intercepts route transitions before navigation completes to check user authentication or permission meta fields ('to.meta.requiresAuth').

Code Implementation Example

typescript
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', component: () => import('@/views/LoginView.vue') },
    { path: '/dashboard', component: () => import('@/views/DashboardView.vue'), meta: { requiresAuth: true } }
  ]
});

// Global Authentication Navigation Guard
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('auth_token');
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});
💡Configuring Vue Router 4 with global beforeEach navigation guards for route protection.
🎯 Interview Key Takeaway

Use createRouter with createWebHistory() and router.beforeEach() navigation guards to protect authenticated routes.

#Vue Router#Navigation Guards#Routing#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?