Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

VueJS - Route Guards

Using Route Guards for Navigation Control

Route guards in VueJS are used to control navigation and access to certain routes. They allow you to execute code before a route is entered, left, or updated. This guide covers the different types of route guards and how to use them effectively.

Key Points:

  • Route guards provide control over navigation and can be used for authentication, authorization, and other checks.
  • There are three main types of route guards: global guards, per-route guards, and in-component guards.
  • Understanding and utilizing route guards is essential for building secure and robust applications.

Global Guards

Before Each

The beforeEach guard is called before every navigation. It can be used to perform checks or redirect users:


// src/main.js
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

Vue.config.productionTip = false;
Vue.use(VueRouter);

const routes = [
  // Define your routes here
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  // Perform checks or redirect
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

new Vue({
  router,
  render: h => h(App),
}).$mount('#app');

function isAuthenticated() {
  // Replace with actual authentication check
  return false;
}
                

Before Resolve

The beforeResolve guard is similar to beforeEach but is called right before the navigation is confirmed:


router.beforeResolve((to, from, next) => {
  // Perform final checks or preparations
  next();
});
                

After Each

The afterEach guard is called after every navigation. It does not affect the navigation itself:


router.afterEach((to, from) => {
  // Perform actions after navigation
  console.log('Navigation completed');
});
                

Per-Route Guards

Per-route guards are defined directly in the route configuration and apply only to specific routes:


// src/main.js
const routes = [
  {
    path: '/protected',
    component: ProtectedComponent,
    beforeEnter: (to, from, next) => {
      // Perform checks or redirect
      if (!isAuthenticated()) {
        next('/login');
      } else {
        next();
      }
    }
  }
];
                

In-Component Guards

In-component guards are defined within the component and allow you to handle navigation events specific to that component:


// src/components/ProtectedComponent.vue



                

Example Application

Here is an example application demonstrating the use of route guards for authentication:


// src/main.js
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import LoginComponent from './components/LoginComponent.vue';
import ProtectedComponent from './components/ProtectedComponent.vue';

Vue.config.productionTip = false;
Vue.use(VueRouter);

const routes = [
  { path: '/login', component: LoginComponent },
  {
    path: '/protected',
    component: ProtectedComponent,
    meta: { requiresAuth: true }
  }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

new Vue({
  router,
  render: h => h(App),
}).$mount('#app');

function isAuthenticated() {
  // Replace with actual authentication check
  return false;
}
                

Best Practices

Follow these best practices when using route guards:

  • Keep Guards Simple: Keep the logic within route guards simple and focused on navigation control.
  • Use Meta Fields: Use meta fields in route definitions to store route-specific information like authentication requirements.
  • Test Guards Thoroughly: Test your route guards to ensure they work as expected and handle edge cases.
  • Document Guards: Document your route guards to make them easier to understand and maintain.
  • Handle Errors Gracefully: Ensure that your guards handle errors gracefully and provide appropriate feedback to users.

Summary

This guide provided an overview of using route guards in VueJS for navigation control, including global guards, per-route guards, and in-component guards. By understanding and utilizing route guards, you can build secure and robust VueJS applications.