Every time I attempt to navigate to the login page, I find myself stuck in an endless loop

This code snippet demonstrates the router.beforeEach function in action. It checks if the client is authenticated, and if not, it redirects them to the login page.

router.beforeEach(async (to, from, next) => {
  if ( to.name !== 'signup' || to.name !== 'login' ) {
    if (await checkAuth()) {
     next()
    } else {
      next({name: 'login'})
    } 
  } else {
    next()
  } 
})

Answer №1

The reason for the issue lies in how you structure your condition.

When attempting to access the login page without being authenticated, the sequence is as follows:

  • 'login' does not equal 'signup' (true)
  • await checkAuth() (false)
  • proceed with next steps({ name: 'login' })

You might have intended:

const authorizedPages = []
const guestPages = ['login', 'signup']
const isAuthenticated = await checkAuth()

if (authorizedPages.includes(to.name)) {
  if (isAuthenticated) {
    next()
  } else {
    next({ name: 'login' })
  }
} else if (guestPages.includes(to.name)) {
  if (isAuthenticated) {
    next({ name: 'home' })
  } else {
    next()
  }
} 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

Manipulating the DOM with Javascript and jQuery: Adding a new element and retrieving its reference

I am encountering an issue with a Web App that relies on JavaScript and jQuery. Essentially, the website includes a button that triggers a JavaScript function when clicked. Within this function, there are two other functions named Foo and Bar. Foo generate ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

Substitute the Iframe element with Ajax technology

Currently, I am working on a project where I want to include previews of various websites within my own website. Right now, I am using Iframes to load the website previews and allow users to interact with them. For SEO purposes, I have decided to replace ...

Evolution of the material through a fresh new slide

Can someone assist me with an animation issue? I have a slideshow consisting of 4 images that are supposed to transition automatically after a set time interval. Upon initially loading the webpage, the animation works perfectly as intended. However, subs ...

Integration of Unlayer EmailEditor into React causes fatal errors in the application

I am attempting to integrate Unlayer into my React Application by using this guide: https://github.com/unlayer/react-email-editor. I have configured Webpack for this purpose. However, when I try to import EmailEditor in one of my modules: import React fr ...

When the input field is in debug mode and has a keydown event listener, the character fails to appear as intended

As a newcomer to javascript/html, I have an input with a keydown event listener. Surprisingly, everything seems to work fine when I try it out in the browser. I type a character and see that my javascript is executed, then I type another character and it w ...

Identify user input with Python Selenium for keyboard and mouse interactions

As a frequent user of Selenium Browser for my everyday browsing needs, I am looking to implement some code that will be triggered when certain keys are pressed on any page. Initially, I considered loading JavaScript onto each page to track key and mouse in ...

app.js at line 81010 triggers a Vue warning because of an error in the mounted hook. The error message states: "ReferenceError: $store is not defined

As part of my code refactoring process to incorporate vuex, I encountered 2 errors: app.js:81010 [Vue warn]: Error in mounted hook - "ReferenceError: $store is not defined" and ReferenceError: $store is not defined. Despite thinking that I imported vuex co ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

Troubleshooting: EADDRNOTAVAIL issue encountered on Heroku Node.js server

After successfully creating a nodejs server on OpenShift, I am now embarking on a new project and attempting to replicate the same server on Heroku. Below is a snippet of the code for my server: var http = require('http'); var port = process.en ...

What is the best way to access elements and attributes from a specific JSON file?

Is there a way to access each property within the JSON data provided? Additionally, I am interested in filtering specific objects based on their IDs. How can this be achieved using the array.filter method in JavaScript? { "records": [ ...

Execute a self-invoking JavaScript function with dynamic code

I'm facing a challenging problem that I just can't seem to solve... There's a function on another website that I need to use, but unfortunately, I can't modify it The code in question is: Now, I am looking to add a prototype "aaa" to ...

The FireBase getToken function with the forceRefresh set to true has failed to perform as expected

I encountered a problem with this code snippet from Firebase when trying to run it in Angular 2 CLI. It gives an error of 'unreachable code'. How can I fix this issue and get it to work properly? firebase.auth().currentUser.getToken(/forceRefres ...

Storing client-requested data locally

Is it possible to use JavaScript to make an AJAX request to fetch data from a server, then prompt the user to save this data on their computer for later access outside of the browser session? Can this saving functionality be achieved without using a Flas ...

How to use JavaScript to validate if an input field is empty in IE

I am facing an issue with the required attribute in IE9. While the attribute works fine in IE10 and above, I am struggling to get it to function in IE9. I have attempted the following: $('#submit-button').click(function(){ if($('#message ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

Utilizing cheerio to set outerHTML in HTML

Could someone kindly assist me with setting the outerHTML of an element using cheerio? I seem to be encountering some issues with this process. For example, let's consider the following HTML structure: <div class="page-info"> <s ...

Adding additional validations to your Marketo form is a great way to ensure the accuracy

I'm having trouble adding a new validation rule to the Marketo form since I'm not well-versed in JS and jQuery. I need this rule to display an error message if the form is submitted with any field left empty. Additionally, I want to validate the ...

Having trouble converting a timestamp to a date in JavaScript

My database uses MongoDB and has a timestamp field with unique formats, such as: 1657479170.7300725 1657479170.7301126 1657479170.7301197 1657479170.9120467 1657479170.932398 Converting these timestamps to the date format YYYY-MM-DD yields the correct res ...