#[nuxt3]: Using Pinia Outside Component (in custom js file)

6 messages · Page 1 of 1 (latest)

pulsar hull
#

Hello everyone,

I'm trying to use pinia outside of a component/composable.

The pinia docs suggest that we can install pinia in a router.beforeEach:

router.beforeEach((to) => {
  // This will work because the router starts its navigation after
  // the router is installed and pinia will be installed too
  const store = useStore()

  if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})

Since nuxt uses file routing, I thought the logical thing to do was to put it in a global route middleware:

// middleware/index.global.ts
import { useSessionStore } from "~/stores/session.store"

export default defineNuxtRouteMiddleware((to, from) => {
  const sessionStore = useSessionStore()
})

But I still get this error:
getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production.

Any idea on how I can resolve this? Thank you.

muted rain
pulsar hull
muted rain
#

@pulsar hull you cant have pinia or any nuxt composable for that matter outside of the function that is being called in nuxt context

pulsar hull
#

Ah