Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue-router.esm.js?xxx RangeError: Maximum call stack size exceeded':

router.beforeEach( (to, from, next) => {
      if(store.getters.getUser == null || store.getters.getUser == undefined ){
        next('/welcome',)
      }
        else return  next()
    }
);

I also tried using a beforeEnter hook in my router.js file for each path, but despite functioning properly, whenever I refresh the page, it redirects me to the login page ('welcome') even though the user is already logged in. Here is the code snippet:

import store from '../store/index'


Vue.use(VueRouter)

const routes = [
  { 
    path: '/',
    name: 'home',
    component: Home,
    beforeEnter:(to, from, next) => {
      if (store.getters.getUser == null || store.getters.getUser == undefined ){
        next('/welcome',)
      }
        else return  next()
    }
  },
   path: '/chat',
    name: 'chat',
    component: Chat,
    beforeEnter:(to, from, next) => {
      if(store.getters.getUser == null || store.getters.getUser == undefined ){
        next('/welcome',)
      }
        else return  next()
    }
  }...etc...
  ]

Answer №1

It was a challenge for me to come up with a solution that would redirect users to the home page regardless of which link they clicked on. After trying various techniques found online and hitting dead ends, I decided to hard code a forced exit scenario. Although not the most conventional approach, it did the trick by ensuring that I always ended up on the home page no matter where I started from.

router.js file

import store from '../store/index'

Vue.use(VueRouter)

const routes = [
  { 
    path: '/',
    name: 'home',
    component: Home,
    beforeEnter:((to, from, next)=>{
      if(store.getters.getUser == null || store.getters.getUser == undefined ){
        next ('/welcome',)
      }
      else next ()
    })
  },
  {
    path: '/about',
    name: 'about',
    component:About,
  },
  {
    path: '/chat',
    name: 'ChatRoom',
    component:ChatRoom,
    beforeEnter:((to, from, next) => {
      if(store.getters.getUser == null || store.getters.getUser == undefined ){
        next ('/welcome',)
      }
      else next()
    })
  },
  {
    path: '/results/:idItemSelected',
    name: 'SearchResults',
    component:SearchResults,
    props:true,
    beforeEnter:((to, from, next) => {
      if(store.getters.getUser == null || store.getters.getUser == undefined ){
        next ('/welcome',)
      }
      else next()
    })

  },
  {
    path: '/welcome',
    name: 'WelcomingPage',
    component:WelcomingPage,

  },
]

On my WelcomingPage view, I implemented a watcher to detect when a user is authenticated and then automatically redirect them to the home page:

computed: {
    ...mapGetters(["getUser"]),

user(){ 
  return this.$store.getters.getUser
}

watch:{
    user(value) {
      if(value != null||value != undefined){
          this.$router.push('/')
      }
      else{
        return this
      }
    },

This solution has its flaws, so I'm open to suggestions for a more efficient way to handle this situation. Any tips or advice would be greatly appreciated! Thank you in advance.

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

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Utilizing Observable Data in Angular 4 TypeScript Components

Looking to extract and assign a JSON value obtained from an API into a variable. Here is an example: TS this.graphicService.getDatas().subscribe(datas => { this.datas = datas; console.log(datas); }); test = this.datas[0].subdimensions[0].entr ...

What is the best way to retrieve the ID of a conditionally displayed item within a modal component?

I am facing an issue with my notes component where I need to delete a specific note based on its ID after accepting a modal confirmation. It works fine without the modal, but I want to ensure that the note is only deleted when the modal is accepted. This ...

Troubleshooting the Issue of PHP Variables Not Being Assigned to Javascript Variables

I am currently struggling with an issue. I am trying to assign a PHP value to a variable in Javascript. Here is what I have attempted: <script> JSvariable = <?php echo $PHPvariable; ?>; </script> However, this approach is not yieldi ...

What is the recommended depth in the call stack to utilize the await keyword for an asynchronous function?

My knowledge of async functions in TypeScript/React is fairly basic. I have two API calls that need to be made, and I am using async functions to call them from my UI. It's crucial for these calls to have completed before rendering the component corre ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

The 'in' operand is invalid

I am encountering a JavaScript error: "[object Object]" TypeError: invalid 'in' operand a whenever I attempt to perform an AJAX request using the following code: .data("ui-autocomplete")._renderItem = function( ul, item ) { return $( " ...

Exploring the Power of v-for in Nested Objects with Vue

I currently have a dataset in the following structure: itemlist : { "dates": [ "2019-03-15", "2019-04-01", "2019-05-15" ], "id": [ "arn21", "3sa4a", "wqa99" ], "price": [ 22, 10, 31 ] } My goal is t ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...

What is the best way to eliminate whitespaces and newlines when using "document.execCommand("copy")" function?

I'm currently working on a code that allows users to copy highlighted text without using the keyboard or right-clicking. I also need to remove any extra spaces or line breaks using regex after the text is selected. However, I am facing some issues wit ...

What is the process for importing a JavaScript export file created from the webpack.config file?

Issue at Hand In the process of testing APIs, I encountered a dilemma in setting up either the DEV or Production environment. This involved configuring API endpoints for local testing and preparing them for production use. To achieve this, I utilized NOD ...

Creating a visually appealing label by customizing it according to the child div

Can the label be styled based on whether the input is checked or not using CSS, or do I have to use JavaScript? <label class="filterButton"> <input name="RunandDrive" type="checkbox" value="1"> </label> ...

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

Using Vue.js to make AJAX requests

I am facing an issue while trying to fetch data from an API endpoint api/data which returns an object. However, when I run my application, nothing shows up in the console and there are no XHR requests visible in the network tab. There are no warnings or er ...

Determine which JavaScript script to include based on whether the code is being executed within a Chrome extension

I am in the process of developing a Chrome extension as well as a web JavaScript application. I currently have an HTML container. I need the container.html file to include <script src="extension.js"> when it is running in the Chrome extension, and ...

Issue with resetting Knockout.JS array - unable to make it work

Hey everyone, check out the project I'm currently working on over at Github: https://github.com/joelt11753/Udacity-map In this project, I have a menu generated from a list that can be filtered using an HTML select element. Initially, all items are di ...

Continuously monitor the condition in my function

I'm encountering an issue with my jQuery function where it animates a progress bar from 0 to 100 when it's visible on the screen. The problem arises when the progress bar is not initially visible upon page load, as the animation will never trigge ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...