#Pinia Global Middleware

10 messages · Page 1 of 1 (latest)

open jasper
#

Hey I'm using Nuxt 3.0.0 and have this in auth.global.ts in /middleware:


export default defineNuxtRouteMiddleware((to, from) => {
  const accessToken = computed(() => useUserStore().$state.accessToken);
  console.log(useUserStore().$state);
}```

And on refresh, the $state is giving the initial state and not the current state, so accessToken is always undefined even if my user is logged in. What am I doing wrong? I know Pinia is instantiated after middlewares but I see examples of people doing this online but can't see why mine isn't working this way.
wispy wasp
#

Maybe rather than having a computed property, you could add a getter in your store for the token?

open jasper
wispy wasp
#

Not necessarily, no, but how the token is stored/obtained in your store might have something to do with it too.

#

Maybe you can create a reproduction on https://nuxt.new of just the store and the middleware and see if it happens there

Start a Nuxt project

The best way to get started with a new Nuxt project.

open jasper
wispy wasp
#

Well, there's a difference between server middleware and route middleware in Nuxt 3 that's different from how middleware worked in Nuxt 2.

#

Server middleware doesn't return anything, but you might provide the token that way.
https://nuxt.com/docs/guide/directory-structure/server#server-middleware

Something like:

// server/middleware/token.ts
const pinia = createPinia()

export default defineEventHandler((event) =>
  serverPrefetch() {
    const store = useUserStore(this.$pinia)
  },
  event.context.accessToken = useUserStore.accessToken
})
#

and then you'd have the accessToken on the event server side, theoretically

#

I'm not sure the above code will work, but that's the general direction I'd work from