Is It Okay to Have Multiple beforeEach Guards ? #2424
-
Hi I'm working on a Vue/Vite/Vue router project where I need to perform multiple tasks in my beforeEach guards, such as setting page metadata and handling authentication using Keycloak. I want to make the guards efficient, especially avoiding unnecessary checks in non-production environments. Here's my current approach: if (import.meta.env.PROD) {
router.beforeEach(async (to) => {
if (!router.keycloak.authenticated) {
await router.keycloak.login()
}
})
}
router.beforeEach(async (to) => {
setPageTitle(to.meta.title)
setPageDescription(to.meta.description)
}) My Questions:
I don't think combining all logic into a single beforeEach guard with conditional branches would be more efficient or readable, but i'd like to have your opinion. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
From the docs:
https://router.vuejs.org/guide/advanced/navigation-guards.html#Global-Before-Guards
I'm not sure I understand what you mean by "without duplicating unnecessary logic in development"? You mean using another approach than the To my knowledge this is the most standard approach for this, and this is pretty efficient from a performance standpoint because most bundlers will remove that code if condition is
I think it's personal preference and both can be pretty readable as long as you just have simple function calls (and not verbose, complex, hard-to-read code). Regarding the performance impact of using a single vs multiple -- So to make it short:
|
Beta Was this translation helpful? Give feedback.
From the docs:
https://router.vuejs.org/guide/advanced/navigation-guards.html#Global-Before-Guards
I'm not sure I understand what you mean by "without duplicating unnecessary logic in development"? You mean using another approach than the
if (import.meta.env.PROD)
condition?To my knowledge this is the most standard approach for this, and th…