[Vuejs]-Browser freezes using beforeEach

2👍

The docs say "you must call next exactly once" 1. If the first if is true, it’s called twice. If the second or third ifs are true, it gets called three times.

You might need to return inside the ifs to avoid that. Or use else statements.

Update to add examples:

Here’s an example using else (preferable if you’re on v3.x):

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" });
    } else if (
      (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
      !userGroup
    ) {
      next({ path: "/" });
    } else {
      next();
    }
  } else {
    next();
  }
});
export default router;

1: For the current version (v4.x), the docs also say that next was supposed to be removed, according to this RFC. I don’t see a deprecation warning, but using it is discouraged.

In that case, this is a better solution for the current version:

router.beforeEach((to, from) => {
  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") {
      return { path: "/login" };
    }
    
    if (
      (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
      !userGroup
    ) {
      return { path: "/" };
    }
  }
});
export default router;

2👍

As you’re not using ‘else’ statements, you’re calling next() multiple times and hitting an infinite loop (as mentioned in the comments).

You can return instead to stop the code at that 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;

Leave a comment