Unveiling the secrets of leveraging Vue Router global navigation guard to efficiently verify multiple conditions

Within a Vue 3 application utilizing Pinia, my objective is to accomplish the following:

  1. Direct a user to the sign-in page when authentication is not verified.
  2. Direct a user to a verification page if authenticated but not yet verified.
  3. Direct a user to the dashboard upon successful authentication and verification.

Currently, I have successfully set up redirects for unauthenticated users to the sign-in page and verified users to the dashboard by configuring my router index.js file as follows:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/signin",
            name: "signin",
            component: () => import("../views/SignIn.vue"),
        },
        {
            path: "/verify",
            name: "verify",
            component: () => import("../views/Verification.vue"),
            meta: { needsAuth: true }
        },
        {
            path: "/dashboard",
            name: "dashboard",
            component: () => import("../views/UserDashboard.vue"),
            meta: { needsAuth: true }
        }
    ]
})

router.beforeEach(async (to, from, next) => {
    if (to.meta.needsAuth && localStorage.getItem('accessToken') == null) next('signin')
    else next()
})

export default router

Additionally, here is the method responsible for handling sign-ins:

const loginUser = async () => {
  try {
    const res = await axios.post(
      "https://some-api-url/login",
      signin.value,
      {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      }
    );

    localStorage.setItem("accessToken", res.data.data.accessToken);

    // Redirect to the dashboard
    router.push("/dashboard");
  } catch (error) {
    error = error.response.data.message;
    alert(error);
  }
};

Now, the challenge I am facing is that the sign-in endpoint only returns an access token, while the dashboard endpoint returns the verification status. How can I implement redirects for unverified users to the verification page?

Answer №1

One method I found effective in ensuring an authenticated but unverified user gets redirected to the verification page is by implementing a pre-route guard specifically for the dashboard section:

{
    path: "/dashboard",
    name: "dashboard",
    component: () => import("../views/UserDashboard.vue"),
    meta: { needsAuth: true },
    beforeEnter: (to, from, next) => {
        if (localStorage.getItem('verified') == "false") next('verify')
    }
}

This setup operates by the global guard verifying the user's authentication status, while the pre-route guard focuses on checking the user's verification status. Though functional, I wonder if this approach might not be the most efficient given the multiple routes that require user verification.

Could achieving this same functionality within the global guard itself be a feasible option? It's an interesting query to ponder within what was meant to be a straightforward response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Safari not updating Angular ng-style properly

I created a simple carousel using Angular and CSS animations which works well in Chrome. However, I recently tested it in Safari and noticed that the click and drag functionality does not work. I've been trying to fix this issue for days and could use ...

Accessing JavaScript variables within Selenium

Currently utilizing Selenium Webdriver 2.0 to test an HTML page that incorporates an x.js file. Within x.js, the variable "price" is defined based on data entered from the HTML form and various Javascript calculations. In the HTML, the correct price valu ...

The keyboard automatically disappeared upon clicking the select2 input

Whenever I select the select2 input, the keyboard automatically closes $('select').on('select2:open', function(e) { $('.select2-search input').prop('focus',false); }); Feel free to watch this video for more i ...

Ensure that a JavaScript prompt appears when a form is selected in a dynamic HTML field

My PHP script generates a table form with results from a database query for users to edit records. The form can display up to 30 records. If the VoidTag checkbox is checked when the form is submitted, I want the user to confirm this action. If it is not ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

Retrieve a JavaScript object based on a specific value

Looking at my object : TeamMember = { 0 : {"ID": 100, "Name": "MNO", "Role": 2}, 1 : {"ID": 101, "Name": "PQR", "Role": 3}, 2 : {"ID": 103, "Name": "STU", "Role": 3} } I am trying to retrieve TeamMember[1] : {"ID": 101, "Name": "PQR", "Role": 3} a ...

Arranging elements based on specific coordinates

const renderTimeSlots = () => { const timeSlots = []; for (let i = parseInt(workStartsAt); i <= parseInt(workEndsAt); i++) { if (i !== 0) { timeSlots.push( <div className="flex flex-row cursor-pointer"> ...

The `this` keyword is incapable of accessing the object. It is instead pointing to the `window` object

Here is a sample of Javascript constructor code: function TestEngine() { this.id='Foo'; } TestEngine.prototype.fooBar = function() { this.id='bar'; return true; } TestEngine.prototype.start = function() { this.fooBar( ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

Implementing Conditional ng-src Loading based on a Given Value

I have a dropdown menu that contains a list of image names. When an image is selected, it should be loaded and displayed using the ng-src directive. Everything works perfectly fine when a name is chosen. The issue arises when the dropdown menu also includ ...

Sharing a variable with JavaScript within an OnClick event to update a progress bar in C#

When I click on a button, a JavaScript function is launched to create a progress bar. <asp:Button ID="btn_tel" runat="server" CausesValidation="False" OnClick="btn_telefono" Text="Check" CssClass="button" OnClientClick="move()" /></div> The f ...

Is there a way to split a string into words using arrays and functions?

The code I am currently working on is as follows: function look(str) { var stringArr = ['JAVA']; var arr = []; var novaString = '' for(i = 0; i < stringArr.length; i++) { arr = stringArr; } console.log(arr) return ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

Learn the process of dynamically wrapping component content with HTML tags in Vue.js

Hey there! I'm looking to enclose the content of a component with a specific HTML tag, let's say button for this scenario. I have a function that dynamically returns a value which I use as a prop. Based on that, I want to wrap the component&apos ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Using Vue file to access a custom JavaScript object

I have a specialized entity called Plan that is utilized across various files in my project. Currently, I redundantly redefine the entity Plan wherever it's needed. This approach is not efficient, so I decided to consolidate this entity into a single ...

What are the steps to incorporate web components into a Vue project with Typescript?

I am currently facing an issue with integrating a web component into my Vue project. Despite seeing the element in the DOM, it appears as an empty tag instead of the button it should be. The first error I encountered was the absence of a declared module. ...

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...