user is undefined in middleware
creazy231 opened this issue · 4 comments
creazy231 commented
As the title says: If you want to get the user inside a middleware using const user = useDirectusUser();
the user object is not defined.
Workaround: Use const { fetchUser } = useDirectusAuth();
to fetch the user if user from const user = useDirectusUser();
is undefined.
Version
nuxt-directus: 5.4.4
nuxt: 3.6.1
Reproduction Link
Steps to reproduce
What is Expected?
The user object
What is actually happening?
Intevel commented
That's not a bug, surely you should fetch the user if it's undefined.
creazy231 commented
All right, so wouldn't it be cool to have a feature that fetches the user automatically whenever its requested but is undefined then?
casualmatt commented
Documentation needs to be updated with this example:
export default defineNuxtRouteMiddleware(async (to, _from) => {
const { fetchUser, setUser } = useDirectusAuth();
const user = useDirectusUser();
if (!user.value) {
const user = await fetchUser();
setUser(user.value);
}
if (!user.value) {
return navigateTo("/login");
}
});
Intevel commented
Updated the documentation