Home  >  Q&A  >  body text

Browser becomes unresponsive when using beforeEach

I'm trying to set up some routes in my application that users can and cannot access, but sometimes my browser freezes and won't give me any error messages, so I don't know what I'm doing wrong.

In the first IF, I check if the route requires authentication to true for access, if false, I send the user to the login page. I then check which group the user is in and if that fails, redirect to the root page "/". If none of these IF statements hold true, I just redirect to the page the user wants to navigate to.

router.beforeEach((to, from, next) => {

      const isAuth = localStorage.getItem("auth");
      const userGroupRaw = localStorage.getItem("userData");
      const accessGroup = to.meta.group;
      let userGroup;
      if (userGroupRaw) {
        userGroup = JSON.parse(userGroupRaw).id_access;
      }
    
      if (to.matched.some((record) => record.meta.requiresAuth)) {
        console.log("if1");
        if (isAuth === "false") {
          next({ path: "/login" });
        }
        if (
          (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
          !userGroup
        ) {
          next({ path: "/" });
        }
    
        next();
      }
    
      next();
    });
    export default router;

P粉724256860P粉724256860213 days ago310

reply all(1)I'll reply

  • P粉409742142

    P粉4097421422024-03-20 09:41:36

    Since you are not using an "else" statement, you are calling next() multiple times and getting stuck in an infinite loop (as mentioned in the comments).

    You can use return to stop the code at this point.

    router.beforeEach((to, from, next) => {
    
      const isAuth = localStorage.getItem("auth");
      const userGroupRaw = localStorage.getItem("userData");
      const accessGroup = to.meta.group;
      let userGroup;
      if (userGroupRaw) {
        userGroup = JSON.parse(userGroupRaw).id_access;
      }
    
      if (to.matched.some((record) => record.meta.requiresAuth)) {
        if (isAuth === "false") {
            return next({
                path: "/login"
            });
        }
        if (
            (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
            !userGroup
        ) {
            return next({
                path: "/"
            });
        }
        // next(); - this is not needed as the preceding next always gets called.
      }
      next();
    })
    
    export default router;

    reply
    0
  • Cancelreply