Problem identified with Vue.js: The Log in screen briefly flashes before redirecting the authenticated user (resulting in a full page refresh)

My routing is functioning properly, utilizing navigation guards to prevent users from accessing the login or register routes once they are signed in. However, when I manually type '/auth/signin' in the address bar, the login screen briefly appears before redirecting to the dashboard (due to the beforeEach function detecting that the route requires a guest).

router.beforeEach(function (to, from, next) {
    // prevent access to login & register after signing in
    if (to.matched.some(record => record.meta.requiresGuest)
        && auth.user.authenticated)
    {
        next({
            path: '/dashboard'
        });
    }
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // this route requires auth, check if logged in
        // if not, redirect to login page.
        if (!auth.user.authenticated) {
            next({
                path: '/auth/signin',
                query: { redirect: to.fullPath }
            })
        }
    }
    next() // make sure to always call next()!
});

Is there any way to prevent the component from briefly appearing like that? Doesn't the beforeEach function get triggered before the component is actually created?

Answer №1

Revise the conditional statements in your code.

router.beforeEach(function(to, from, next) {
  // Update access control for login and register routes
  if (to.matched.some(record => record.meta.requiresGuest) && auth.user.authenticated) {
    next({
      path: '/dashboard'
    });
  } else if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.user.authenticated) {
      next({
        path: '/auth/signin',
        query: {
          redirect: to.fullPath
        }
      })
    }
  } else {
    next() // Remember to always include 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

What is the procedure for initiating a POST request when the payload is ready for submission?

After a successful payment, my success page is displayed with a URL that includes a query parameter. I want to make a POST request to my API endpoint when the page loads, but I'm encountering an issue where the first POST request is empty (router.quer ...

Tips for utilizing dynamic key within nested JSON data when binding to v-model in Vue.js?

I'm experiencing difficulties when trying to choose options from a select dropdown using dynamic keys from a multidimensional JSON object: rowsels: {"days":{"mon":{"start":"08:00","end":"18:00"},"tue":{"start":"09:00","end":"15:00"},"fou":{"start":"1 ...

Passing a variable between pages in PHP: a simple guide

In my *book_order* page, I allow users to input orders into a table called *order_management*. The order_id is auto-incremented in this table. After submitting the page, I need to pass the order_id to another page named *book_order2* where products can be ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Some images fail to load on Ember in the production environment

I am facing an issue with my Ember-cli 1.13 application where all images are loading correctly except those in a specific component. The component is named "list-item" and is defined as follows: {{list-item url="list-url" name="List Name" price="240"}} I ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

I am currently exploring next.js and working on creating a dedicated single post page within my project

I am currently working with Next.js and fetching some dummy data on the homepage. However, I am facing an issue when trying to create a separate page for each post obtained from the homepage. Although I have already coded it, I feel like there is room fo ...

Searching for parameters wrongly triggering the id on a different route

Having recently delved into mongoose, I must apologize in advance for any misuse of terminology on my part. Below is the content of my routes file: const express = require('express'); const router = express.Router(); const passport = require(&a ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Styling GeoJSON data in the React Leaflet mapping library can greatly enhance the

I successfully incorporated the leaflet map library into my react project. You can check it out here. I also created a geojson map component as shown below: class MapContainer extends React.Component { state = { greenIcon: { lat: 8.3114, ...

Tips for transferring a variable from a webpage's JavaScript to Node.js

Having an issue with transferring a Javascript variable to node js for JSON file storage. The data doesn't seem to be writing to the file, possibly due to an error in the AJAX Post request or the node JS routing. The javascript is executed on an HTML ...

Using JQUERY to create a dropdown menu that dynamically changes based on the date field

I am currently working on a JQUERY project and facing a challenging situation. I usually know how to create dropdown menus that depend on one another, but this time I need a dropdown menu that displays age ranges based on the date entered in the birth-date ...

Unable to transfer AJAX data to PHP script

Trying to figure out how to send AJAX data to PHP. While I am comfortable with PHP, JavaScript is a bit new to me. Incorporating HTML / JavaScript <input type="text" id="commodity_code"><button id="button"> = </button> <script id="s ...

The element type provided is not valid: it was expecting a string but received undefined. Please review the render method of AnimatedComponent in ReactNavigation

I've been facing an issue for the past few days with ReactNavigation v6+. While there are multiple questions and answers about the invalid element type, none of them seem to be working with this specific example: The problem arose after integrating t ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

merging pictures using angular 4

Is there a way in Angular to merge two images together, like combining images 1 and 2 to create image 3 as shown in this demonstration? View the demo image ...