nuxt: Middleware + pinia not working

Environment

middleware

Reproduction

middleware

Describe the bug

When I reload the page, it throws me to the authorization page, although the user is authorized

import { useAuthStore } from '~/store/auth';

export default defineNuxtRouteMiddleware(async () => {
  const { loggedIn } = useAuthStore();

  if (!loggedIn) {
    return navigateTo('/auth');
  }
});

Additional context

No response

Logs

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 4
  • Comments: 29 (10 by maintainers)

Most upvoted comments

@typhoon11 In your middleware, you should not trigger navigateTo in the “default”/“happy” case. Instead, just not return anything and the middleware will “succeed”.

import { useDiscordUser } from '~/stores/auth';

export default defineNuxtRouteMiddleware(async (to, from) => {
  const app = useNuxtApp();
  const user = await useDiscordUser(app.$pinia);

  if (!user.user) {
    console.log('User not logged in');
    return navigateTo('/');
  }
});

I allow my self to re-open this ticket since the problem has not been solved yet!

@maksimdrosdov Please be aware that a full-blown project is no reproduction 🙈

The goal is to have as little “moving pieces” as possible and a project that is as small as possible to reproduce the bug so contributors can pin it down easily and it is not caused by any custom userland logic