You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In this example, we want to use global middleware to restrict page access based on a user's role. To do this, we define the required roles using definePageMeta, and compare this to the current user's role.
First, in our middleware (middleware/roles.global.ts) we augment the type RouteMeta to define the possible options:
if(allowedRoles===undefined||allowedRoles===0)return;// ERROR: This comparison appears to be unintentional because the types 'string' and 'number' have no overlap.
To protect a page, we can place the following code in a script setup block:
definePageMeta({allowedRoles: 'admin',});
However, this is NOT type safe:
definePageMeta({allowedRoles: 0,// No type error, but fails at runtime.});
Expected behavior definePageMeta should pull in the types from RouteMeta
Describe the bug
When augmenting the types of
RouteMeta
, this type information is not available indefinePageMeta
. I have created a minimal example here: https://stackblitz.com/edit/nuxt-typed-router-issue?file=middleware%2Froles.global.tsIn this example, we want to use global middleware to restrict page access based on a user's role. To do this, we define the required roles using definePageMeta, and compare this to the current user's role.
First, in our middleware (
middleware/roles.global.ts
) we augment the typeRouteMeta
to define the possible options:Next, we pull the user data; in this case:
Then, allow access if the user role matches the allowed role
Note that this comparison is type safe:
To protect a page, we can place the following code in a
script setup
block:However, this is NOT type safe:
Expected behavior
definePageMeta
should pull in the types fromRouteMeta
Environnement infos
Example Environment
https://stackblitz.com/edit/nuxt-typed-router-issue?file=pages%2Fadmin.vue,pages%2Fuser.vue,middleware%2Froles.global.ts
Your nuxt.config.ts
Related: #79
The text was updated successfully, but these errors were encountered: