Intevel/nuxt-directus

user is undefined in middleware

creazy231 opened this issue · 4 comments

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?

That's not a bug, surely you should fetch the user if it's undefined.

All right, so wouldn't it be cool to have a feature that fetches the user automatically whenever its requested but is undefined then?

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");
  }
});

Updated the documentation