What is the best way to navigate a user to a different page once they have successfully logged in using Vue 3

Within a vue 3 application utilizing the composition api, I need to implement different actions depending on whether an authenticated user is verified or not. If the user is not verified, they should be directed to the verification page. However, if the user is verified, they should be redirected to the dashboard.

To accomplish this, I have incorporated navigation guards in my router's index.js file:

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

const router = createRouter({
  history: createWebHistory(),
  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 },
      beforeEnter: (to, from, next) => {
        if (localStorage.getItem('verified') == "false") next('verify')
      }
    },
  ],
});

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

export default router

In the script setup of my signin page, I've included the following code:

import { ref } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";

const router = useRouter();
const signin = ref({
    email: null,
    password: null,
});

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

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

        router.push({ name: "dashboard" });
    } catch (error) {
        alert(error.response.data.message);
    }
};

Upon logging in with an unverified user, I am successfully redirected to the verification page as expected. However, when logging in with a verified user, I remain on the signin view instead of being directed to the dashboard.

I am unsure of what could be causing this issue. How can I resolve this routing problem?

Answer №1

Have you attempted using the next() method to check if the user is authenticated:

beforeRouteEnter: (to, from, next) => {
    if (sessionStorage.getItem('authenticated') === 'false') next('authenticate')
    else next()
}

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

Extending Two Classes in Typescript: A Complete Guide

I am looking for a way to efficiently save time by reusing common code across classes that extend PIXI classes within a 2D WebGL renderer library. Object Interfaces: module Game.Core { export interface IObject {} export interface IManagedObject e ...

Encountered an issue while trying to extract data from state - property of null cannot

I'm facing an issue trying to show a navigation item only when a specific flag is true. The problem arises when I attempt to extract data from it, as it returns undefined. Below is the code snippet I have created for this scenario: let navigate = useN ...

Utilize emit to distribute / allocate a variable

I have some variables stored in a file called server.js (and they tend to change frequently). My goal is to pass these variables to client.js whenever the client sends a request (triggers the 'validate' event). Even though the event is triggered, ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

View the picture directly on this page

Currently, I am in the process of creating a gallery and I would like the images to open on top of everything in their original size when clicked by the user. My expertise lies in HTML and CSS at the moment, but I am open to learning JavaScript and jQuery ...

Exploring the various possibilities of establishing multiple types of many-to-many relationships between two tables using Sequelize technology

Working with Sequelize in Node, I am dealing with Users and items. A user can interact with an item in various ways, such as voting or commending, which are distinct actions in this scenario. Initially, I considered having two separate many-to-many relati ...

Is there a way to pass a method along with its specific generic type to RXJS bindCallback?

When trying to pass a function with callback to the rxjs bindCallback function, I encountered an issue with my generic type. Here is the code snippet in question: const obCreator = bindCallback<T>(FakeServer.instance.on<T>); return obCreator(m ...

Encountered an issue while attempting to retrieve data from the HTTP URL

I encountered an issue when trying to make a request to an HTTP URL from another domain using AJAX. Every time I attempt this, I receive an error callback. DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load { ...

Navigating the dynamic components in Vue using dynamic routing

I'm currently developing an application that helps users manage maintenance tasks. I have successfully created a component to display all the data stored in an array of objects. However, I am facing a challenge in redirecting users to different pages ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

Creating a line chart with multiple axes using Chart.js by importing data from a Google Sheet in JSON format

My attempt to visualize the data stored in a Google Sheet using Chart.js resulted in a multi-axis line chart. The data I have looks like this: https://i.stack.imgur.com/F8lC7.png When trying out the following code, I encountered an issue where only the f ...

What are the steps to developing a unique JavaScript function?

Recently, I created a new function. function createGarage(id) { var id = 'data.models.'+id+'.pictures'; $.ajax({ url: 'models.json', type: 'get', dataType: 'json', error: function(data) ...

Determine whether the values in the array are arranged in ascending or descending order

I'm currently working on a code problem where I need to loop over the values of an array and determine whether they are in ascending order, descending order, or neither. The function I've written so far is not giving me the correct results, but I ...

The custom keyword definition for Docker hub is deemed invalid due to the requirement that data.errors must be a boolean

Encountering a similar issue as outlined in this thread, however, the error surfaces solely during the automated docker hub build and not while executing the Dockerfile on my local machine. Despite attempting all suggested fixes, none have resolved the iss ...

Creating components through the command line while managing multiple projects using Angular CLI 6

Currently, I am utilizing the most recent Angular CLI version (v6). Within my codebase resides a collection of applications housed within the projects directory. My objective is to create and organize various modules and components within these projects v ...

The 'function' is not defined in Edge and Explorer browsers

I am currently working on a web page in SharePoint and have encountered an issue where the onclick referenced function throws an error only in Internet Explorer 11 and Microsoft Edge. However, in Chrome, Firefox, and Opera, everything works perfectly fine. ...

Utilizing Vue.js to pass a slot to a customized Bootstrap-Vue Table component

I am currently in the process of developing a wrapper for the bootstrap-vue Table component. This particular component utilizes slots to specify cell templates, similar to the following example: <b-table :items="itemsProvider" v-bind="options"> ...

Is it possible to detect when a user reaches the end of a div without using a scroll event?

Seeking a JavaScript solution that can identify when a user reaches the bottom of a div with overflow: auto. While there are numerous solutions on Stack Overflow utilizing the onscroll event, I am curious if this can be accomplished using newer technology ...

Click on the image to select a radio button option

Query How can I display the appropriate dropdown when clicking on the image or checkbox, while hiding the radio button in the end? I suspect it may be a scoping problem as the options are not appearing correctly even when the radio button is checked. Vie ...

Is there a way to choose elements that are positioned in close proximity to one another?

Check out this block of HTML code: <html> <head></head> <body> <div class="images"> Some text <img src="image1.jpg"> Some text <img src="image2.jpg"> <img src="i ...