Vue · Senior · Question 39 of 75

How do you implement role-based access with route meta?

{ path: "/admin", component: Admin, meta: { roles: ["admin"] } }
router.beforeEach((to) => {
  const roles = to.matched.flatMap((r) => r.meta.roles ?? []);
  if (roles.length && !roles.some(auth.hasRole)) return { name: "forbidden" };
});

Explanation

to.meta is a shallow merge of parent and child meta, so child values overwrite parent ones; to.matched gives each level separately. Type meta via RouteMeta module augmentation.

Further reading

Problem with a question

Vue · Senior · question 39

Test yourself

Take the Vue · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz