Protecting Routes with Guards

Tutorial 4 of 5

Tutorial: Protecting Routes with Guards in Vue Router

1. Introduction

In this tutorial, we will learn about route guards in Vue Router and how to use them to restrict access to certain routes based on user authentication. This is a common pattern in web applications where you want to restrict access to certain resources unless the user is authenticated.

Objective

  • Understand what route guards are and their role in Vue applications.
  • Learn how to use route guards to protect routes based on user authentication.

Prerequisites

  • Basic understanding of Vue.js and Vue Router.
  • Basic understanding of JavaScript programming.

2. Step-by-Step Guide

Route guards are a feature of Vue Router that allows you to run logic before a route is loaded. You can use this feature to check if a user is authenticated before letting them access a route.

Here is a simple way to implement route guards in Vue:

  • Global Guards: These are applied to every route in your application.
  • Per-Route Guard: These are applied to individual routes.

In this tutorial, we will focus on per-route guards as they give more flexibility.

3. Code Examples

Example 1: Basic Route Guard

const router = new VueRouter({
  routes: [
    {
      path: '/protected-route',
      beforeEnter: (to, from, next) => {
        // This is a route guard
        if (isAuthenticated) {
          next(); // allow access to route
        } else {
          next('/login'); // redirect to login
        }
      }
    }
  ]
});

Explanation:

  • beforeEnter is the route guard here. It's a function that gets called before the route is loaded.
  • isAuthenticated is a hypothetical function that checks if the user is authenticated.
  • next() is a function you call when you're done. If you pass a path to next(), Vue Router will redirect to that path.

Example 2: Using Route Meta Fields

Another way to protect routes is by using meta fields.

const router = new VueRouter({
  routes: [
    {
      path: '/protected-route',
      meta: { requiresAuth: true }
    }
  ]
});

Then in a global guard, you can check if a route requires authentication.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // This route requires auth, check if logged in
    // if not, redirect to login page.
    if (!isAuthenticated()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next(); // make sure to always call next()!
  }
});

In the example above, we're using the beforeEach hook, which is a global guard that gets called before each navigation.

4. Summary

We've learned about route guards and how to use them to protect routes in Vue applications. We've also seen how to use route meta fields to specify which routes require authentication.

For further learning, you can explore other types of route guards like beforeResolve and afterEach.

5. Practice Exercises

Exercise 1: Create a Vue application with two routes, one that requires authentication and one that doesn't. Implement route guards to protect the authenticated route.

Exercise 2: Add a login route to the application from exercise 1. Redirect unauthenticated users who try to access the protected route to the login route.

Exercise 3: Refactor the application from exercise 2 to use route meta fields to specify which routes require authentication.

Solutions: These exercises are open-ended and solutions may vary. The important part is to understand how to use route guards to protect routes.

Tip: To test your route guards, you can create a mock isAuthenticated function that returns true or false based on some condition. This could be a button that toggles the authentication state.