JAVASCRIPT

Programmatic Navigation and Global Route Guards in Vue Router 4

Implement programmatic navigation and global `beforeEach` route guards in Vue Router 4 to control access and redirect users based on application logic.

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', component: () => import('../views/Home.vue') },
  { path: '/dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } },
  { path: '/login', component: () => import('../views/Login.vue') }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('userToken'); // Example: check for a token
  if (to.meta.requiresAuth && !isAuthenticated) {
    // If the route requires authentication and the user is not authenticated, redirect to login
    next('/login');
  } else if (to.path === '/login' && isAuthenticated) {
    // If user is already authenticated and tries to access login, redirect to dashboard
    next('/dashboard');
  } else {
    next(); // Proceed to the route
  }
});

export default router;

// MyComponent.vue (for programmatic navigation)
<template>
  <div>
    <h1>Welcome!</h1>
    <button @click="goToDashboard">Go to Dashboard</button>
    <button @click="goToLogin">Login Page</button>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const goToDashboard = () => {
  router.push('/dashboard');
};

const goToLogin = () => {
  router.push({ name: 'login-route-name' }); // Using named routes
};
</script>
How it works: This snippet illustrates how to use programmatic navigation and global route guards in Vue Router 4. Programmatic navigation allows you to move between routes using `router.push()`, either with a path string or a named route object. The `router.beforeEach` global guard intercepts navigation attempts, enabling you to implement logic (like authentication checks) before a user accesses a route, redirecting them if necessary.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs