Home > front end >  Vue Global Route Guard using beforeEach does not trigger
Vue Global Route Guard using beforeEach does not trigger

Time:10-06

I have a route guard that works when calling it per-route using beforeEnter but does not work when calling it as a global route guard using beforeEach.

In my code at the top you can see the example that works when calling the /dashboard redirect.

But if I try calling it globally on all routes down at the bottom of my code using beforeEach it does nothing.

What am I doing wrong?

P.S. I am using TypeScript.

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Mutations, Actions } from "@/store/enums/StoreEnums";
import { Auth0 } from "@/auth";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/dashboard",
    component: () => import("@/layout/Layout.vue"),
    //beforeEnter: Auth0.routeGuard, // <--- THIS WORKS
    children: [
      {
        path: "/dashboard",
        name: "dashboard",
        component: () => import("@/views/Dashboard.vue"),
      },
      {
        path: "/add-post",
        name: "add-post",
        component: () => import("@/views/Builder.vue"),
      },
    ],
  },
  {
    // the 404 route, when none of the above matches
    path: "/404",
    name: "404",
    component: () => import("@/views/crafted/authentication/Error404.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404",
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(() => {

  store.commit(Mutations.RESET_LAYOUT_CONFIG);

  Auth0.routeGuard; // <--- THIS DOES NOT WORK

  store.dispatch(Actions.VERIFY_AUTH);

  // Scroll page to top on every route change
    setTimeout(() => {
    window.scrollTo(0, 0);
  }, 100);

});

export default router;

CodePudding user response:

router.beforeEach(() => { Auth0.routeGuard; }) has no effect because the Auth0.routeGuard function is not actually being invoked in that statement. Functions are normally called with parentheses surrounding any arguments (e.g., Auth0.routeGuard(arg1, arg2, arg3)).

Solution

The route guard needs to be invoked with the navigation guard arguments from router.beforeEach:

import { RouteLocationNormalized } from 'vue-router'
⋮
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: Function) => {
  ⋮
  Auth0.routeGuard(to, from, next)
  ⋮
})
  • Related