Table of Contents
Routing Basics
Global Guard
Route exclusive guard
Component Guard
Protect routing
Routing structure
Remember the source
notify
in conclusion
Home Web Front-end CSS Tutorial Protecting Vue Routes with Navigation Guards

Protecting Vue Routes with Navigation Guards

Apr 19, 2025 am 10:29 AM

Protecting Vue Routes with Navigation Guards

Security authentication of web applications is crucial. It enables a personalized experience, loads user-specific content (such as login status), and can also be used to evaluate permissions to prevent unauthorized users from accessing private information.

Applications typically protect content by placing content under a specific route and building redirection rules, directing users to access or away from resources based on their permissions. In order to reliably place content behind protected routes, independent static pages need to be built. In this way, the redirection rules can handle redirection correctly.

For single page applications (SPAs) built with modern front-end frameworks such as Vue, redirect rules cannot be used to protect routing. Because all pages come from a single entry file, from a browser's point of view, there is only one page: index.html. In SPA, routing logic usually originates from routing files. This article will mainly configure authentication here. We will specifically rely on Vue's navigation guards to handle authentication specific routes, as this helps us access selected routes before the route is fully parsed. Let's dig into how it works.

Routing Basics

Navigation Guard is a specific feature in Vue Router that provides additional features about how routing resolves. They are primarily used to handle error states and seamlessly guide users without abruptly interrupting their workflow.

There are three major categories of guards in Vue Router: global guards, router exclusive guards and component guards. As the name implies, the global guard is called when triggering any navigation (i.e. when the URL changes), the route exclusive guard is called when calling the associated route (i.e. when the URL matches a specific route), and the component guard is called when creating, updating, or destroying components in the route. In each category, there are other ways to give you more granular control over application routing. Here is a quick breakdown of all the methods available in each navigation guard in Vue Router.

Global Guard

  • beforeEach : Operation before entering any route (this scope cannot be accessed)
  • beforeResolve : Action before navigation confirmation, but after component guard (same as beforeEach, with access to this scope)
  • afterEach : Operation after routing resolution (cannot affect navigation)

Route exclusive guard

  • beforeEnter : Operation before entering a specific route (unlike the global guard, this guard can access this)

Component Guard

  • beforeRouteEnter : Actions performed before navigation confirmation and before component creation (this cannot be accessed)
  • beforeRouteUpdate : The operation performed after calling a new route using the same component
  • beforeRouteLeave : Operation before leaving the route

Protect routing

To implement them effectively, it will be helpful to know when to use them in any given scenario. For example, if you want to track page views for analysis, you might want to use the global afterEach guard because it is triggered after the route and related components are fully parsed. If you want to prefetch data into Vuex storage before route parsing, you can use the beforeEnter route exclusive guard to do so.

Since our example deals with protecting specific routes based on user access rights, we will use component guards, i.e., beforeEnter hooks. This navigation guard allows us to access the correct route before parsing is complete; this means we can get data or check if the data is loaded before allowing the user to pass. Before digging into the implementation details of how it works, let's briefly take a look at how the beforeEnter hook is incorporated into our existing routing files. Below is our sample routing file containing our protected routes, aptly named protected. We will add the beforeEnter hook to it as follows:

 const router = new VueRouter({
  routes: [
    ...
    {
      path: "/protected",
      name: "protected",
      component: import(/* webpackChunkName: "protected" */ './Protected.vue'),
      beforeEnter(to, from, next) {
        // Logic here}
    }
  ]
})
Copy after login

Routing structure

The structure of beforeEnter is no different from other navigation guards available in Vue Router. It accepts three parameters: to , the "future" route to which the application is navigating; from , the "current/imminent past" route to which the application is leaving; next , the function that must be called to make the route resolve successfully.

Generally, when using Vue Router, next is called without any arguments. However, this assumes a permanent state of success. In our case, we want to ensure that unauthorized users are unable to access protected resources and that there are alternative paths that can be properly redirected. To do this, we will pass a parameter to next. To do this, we will use the route name to navigate the user, if they are unauthorized, it looks like this:

 next({
  name: "dashboard"
})
Copy after login

Let's assume in our example we have a Vuex store where we store the user's authorization token. To check if the user has permissions, we will check this store and fail appropriately or through the route.

 beforeEnter(to, from, next) {
  // Check vuex storage//
  if (store.getters["auth/hasPermission"]) {
    next()
  } else {
    next({
      name: "dashboard" // Return to secure route//
    });
  }
}
Copy after login

To ensure that events occur synchronously and that the route does not load prematurely until the Vuex operation is complete, let's convert the navigation guard to use async/await.

 async beforeEnter(to, from, next) {
  try {
    var hasPermission = await store.dispatch("auth/hasPermission");
    if (hasPermission) {
      next()
    }
  } catch (e) {
    next({
      name: "dashboard" // Return to secure route//
    })
  }
}
Copy after login

Remember the source

So far, our navigation guards have achieved their purpose of preventing them from accessing protected resources by redirecting unauthorized users to where they might be from (i.e., dashboard pages). Even so, such a workflow is destructive. Since the redirection is unexpected, the user may think it is a user error and try to access the route repeatedly, ultimately thinking that the application is corrupted. To solve this problem, let's create a method to let users know when and why they are redirected.

We can do this by passing query parameters to the next function. This allows us to attach the protected resource path to the redirect URL. So if you want to prompt the user to log in to the app or get the right permissions without remembering where they stopped, you can do so. We can access the path of the protected resource through the to route object passed to the beforeEnter function, as shown below: to.fullPath.

 async beforeEnter(to, from, next) {
  try {
    var hasPermission = await store.dispatch("auth/hasPermission");
    if (hasPermission) {
      next()
    }
  } catch (e) {
    next({
      name: "login", // Return to secure route//
      query: { redirectFrom: to.fullPath }
    })
  }
}
Copy after login

notify

The next step in enhancing the workflow for users to not have access to protected routes is to send them messages to let them know about the error and how to resolve the issue (by logging in or getting the correct permissions). To do this, we can use component guards, especially beforeRouteEnter, to check if redirects have occurred. Since we pass the redirect path as a query parameter to our routing file, we can now check the routing object to see if the redirect has occurred.

 beforeRouteEnter(to, from, next) {
  if (to.query.redirectFrom) {
    // Do something//
  }
}
Copy after login

As I mentioned earlier, all navigation guards must call next to make the route resolve. As we saw earlier, the advantage of next function is that we can pass an object to it. What you may not know is that you can also access Vue instances in next function. Wow! This is what it looks like:

 next(() => {
  console.log(this) // this is a Vue instance})
Copy after login

You may have noticed that when using beforeEnter, you are not technically accessing this scope. While this may be the case, you can still access the Vue instance by passing the vm to the function, like so:

 next(vm => {
  console.log(vm) // this is a Vue instance})
Copy after login

This is especially convenient because you can now easily create and properly update data properties with relevant error messages without any additional configuration. Using this method, you will get a component like this:

<template><div>
    {{ errorMsg }}

    ...

  </div>
</template>

<script>
export default {
  name: "Error",
  data() {
    return {
      errorMsg: null
    }
  },
  beforeRouteEnter(to, from, next) {
    if (to.query.redirectFrom) {
      next(vm => {
        vm.errorMsg =
          "对不起,您没有访问请求路由的权限"
      })
    } else {
      next()
    }
  }
}
</script>
Copy after login

in conclusion

The process of integrating authentication into your application can be tricky. We explain how to prevent unauthorized users from accessing routes and how to build a workflow based on user permissions to redirect users to or away from protected resources. So far, our assumption is that you have configured authentication in your application. If you haven't configured it yet, and you want to get it up and running quickly, I highly recommend using Authentication as a Service. There are some providers like Netlify's authentication widget or Auth0's lock.

The above is the detailed content of Protecting Vue Routes with Navigation Guards. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles