JAVASCRIPT

Programmatic Navigation and Route Guards in Vue Router 4

Master programmatic navigation and implement powerful route guards in Vue Router 4 for Vue 3 applications to control access and redirect users based on conditions.

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

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

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

// Global Navigation Guard
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('userToken'); // Simulate auth status

  if (to.meta.requiresAuth && !isAuthenticated) {
    // If the route requires auth and user is not authenticated, redirect to login
    next({ name: 'Login', query: { redirect: to.fullPath } });
  } else if (to.name === 'Login' && isAuthenticated) {
    // If user is authenticated and tries to access login page, redirect to dashboard
    next({ name: 'Dashboard' });
  } else {
    next(); // Proceed to route
  }
});

export default router;

// src/views/Home.vue
<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome! You can navigate to the dashboard or login page.</p>
    <button @click="goToDashboard">Go to Dashboard (Programmatically)</button>
  </div>
</template>

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

const router = useRouter();

const goToDashboard = () => {
  router.push({ name: 'Dashboard' });
  // Or with path: router.push('/dashboard');
  // Or with query params: router.push({ path: '/search', query: { q: 'vue' } });
  // router.replace() to navigate without adding to history stack
  // router.go(-1) to navigate back
};
</script>

// main.js (part of setup)
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App).use(router).mount('#app');
How it works: This snippet demonstrates programmatic navigation and route guarding with Vue Router 4. The `router/index.js` file sets up routes and a global `beforeEach` navigation guard. This guard checks if a route requires authentication (via `meta.requiresAuth`) and redirects unauthenticated users to the login page. It also prevents authenticated users from accessing the login page. In `Home.vue`, `useRouter()` provides access to the router instance, allowing navigation using methods like `router.push()` to programmatically change routes, offering precise control over the application's flow.

Need help integrating this into your project?

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

Hire DigitalCodeLabs